Eloquent Many to Many attach函数发送空ID

时间:2016-08-17 19:14:18

标签: php laravel laravel-5.2

我有以下代码尝试将产品附加到product_slot。

$product_slot = new ProductSlot;
$product_slot = $product_slot->where('type', $slot['id'])->first();

$product = new Product;
$product = $product->where('type', (String)$allowed_product)->first();

$product->productSlots()->sync([$product_slot->product_slot_id]);

我可以执行getAttributes()并返回以下内容:

array (size=6)
  'product_slot_id' => int 1
  'type' => string 'breakfastplatter1' (length=17)
  'default_product_id' => string 'bigbfhotcakebiscplat_3590' (length=25)
  'allow_empty' => int 0
  'created_at' => string '2016-08-17 19:04:41' (length=19)
  'updated_at' => string '2016-08-17 19:04:41' (length=19)

array (size=7)
  'product_id' => int 185
  'type' => string 'bigbfhotcakebiscplat_3590' (length=25)
  'label' => string 'Big Breakfast with Hot Cakes (Biscuit)' (length=38)
  'min_option_slots' => int 0
  'max_option_slots' => int 0
  'created_at' => string '2016-08-17 19:05:40' (length=19)
  'updated_at' => string '2016-08-17 19:05:40' (length=19)

以下是产品型号关系:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['type', 'label', 'min_option_slots', 'max_option_slots'];

    public function productSlots()
    {
        return $this->belongsToMany('App\ProductSlot');
    }
}

但是,当我尝试将这些模型同步到一起时,我收到以下错误。

  

SQLSTATE [23000]:完整性约束违规:1048列   ' PRODUCT_ID'不能为null(SQL:插入product_product_slot   (product_idproduct_slot_id)值(,1))

1 个答案:

答案 0 :(得分:2)

您使用自定义主键名称而不是使用id作为主键的Laravel约定。尝试将此添加到您的模型中:

class Product {
    public $primaryKey = 'product_id';
}

class ProductSlot {
    public $primaryKey = 'product_slot_id';
}

另请注意,如果不遵循Laravel约定,有时还需要在定义关系函数时指定非标准主键:

public function productSlots()
{
    return $this->belongsToMany('App\ProductSlot', 'product_slot_id', 'product_id');
}