【问题标题】:Eloquent Many to Many Attach Function sending a Null ID雄辩的多对多附加函数发送空 ID
【发布时间】:2016-08-18 03:45:36
【问题描述】:

我有以下代码试图将产品附加到 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' 不能为空(SQL:插入product_product_slot (product_id, product_slot_id) 值 (, 1))

【问题讨论】:

  • 当然。我马上更新。

标签: php laravel laravel-5.2


【解决方案1】:

您正在使用自定义主键名称,而不是使用 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');
}

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2014-05-23
    • 2017-01-26
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多