Связь один ко многим.
Не могу добиться вывода из связанной таблицы orders.
Ошибка:
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
Модель Customer.php
Код: Выделить всё
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Customer extends ActiveRecord
{
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
/**
* @return string название таблицы, сопоставленной с этим ActiveRecord-классом.
*/
public static function tableName()
{
return 'customer';
}
public function getOrders()
{
return $this->hasMany(Orders::className(), ['customer_id' => 'id']);
}
}
class Orders extends ActiveRecord
{
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
}
Код: Выделить всё
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Customer;
class CustomerController extends Controller
{
public function actionIndex3()
{
// SELECT * FROM `customer` WHERE `id` = 1
$customer = Customer::findOne(1);
// SELECT * FROM `order` WHERE `customer_id` = 1
// $orders - это массив объектов Order
$orders = $customer->orders;
return $this->render('index3', [
'customer' => $customer,
'orders' => $orders,
]);
}
}
view/customer/index3.php
Код: Выделить всё
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<li>
<?= Html::encode("{$orders->orders}") ?>:
</li>
</ul>