Имеется вот такой класс:
Код: Выделить всё
<?php
namespace common\models;
use Yii;
use yii\base\BaseObject;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
class Orders extends ActiveRecord
{
const STATUS_NEW = 0;
const STATUS_PREPARE = 1;
const STATUS_DELIVERY = 2;
const STATUS_WAITING = 3;
const STATUS_COMPLETED = 4;
const STATUS_CANCELED = 5;
public static function tableName()
{
return 'orders';
}
public function rules()
{
.....
}
public function attributeLabels()
{
....
}
public function getStatusLabel()
{
return [
self::STATUS_NEW => 'Новый',
self::STATUS_PREPARE => 'Готовится',
self::STATUS_DELIVERY => 'В доставке',
self::STATUS_WAITING => 'Готов к самовывозу',
self::STATUS_COMPLETED => 'Выполнен',
self::STATUS_CANCELED => 'Отменен',
];
}
public static function find()
{
return new \common\models\query\OrdersQuery(get_called_class());
}
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOrderItems()
{
return $this->hasMany(OrderItems::class, ['order_id' => 'id']);
}
public function add()
{
//Массив товаров в корзине
$productsOrder = [];
/**
* Тут блок кода, который считает доставку, и прочие вычисления от способа доставки...
*/
if ($this->save()) {
//Добавим OrderItems
foreach ($productsOrder as $id => $item) {
$orderItems = new OrderItems();
$orderItems->order_id = $this->id;
$orderItems->goods_id = $id;
$orderItems->quantity = $item['quantity'];
$orderItems->price_unit = $item['price'];
$orderItems->price_total = $item['price'] * $item['quantity'];
if ($orderItems['is_discount']) {
$orderItems->is_discount = true;
$orderItems->price_discount_unit = $item['discount_price'];
$orderItems->price_total_discount = $item['discount_price'] * $item['quantity'];
}
if (!$orderItems->save()) {
return false;
}
}
return true;
}
}
}
Не понимаю почему там NULL, ведь после save() там должен быть id.'
P.S. Если вручную проставить $orderItems->order_id то все работает и добавляется в БД.
Как мне получить этот ID?
В будущем там будет транзакция на добавление.