我正在使用 Laravel 和 Eloquent ORM 开发一个应用程序,它使用一个充满事件信息的数据库。
我已经在我的用户模型和角色模型的相关 Controller 中成功实现了 attach()
。
我的事件模型可以有很多链接。一个链接可以有很多事件。
我的问题是 attach()
没有提供调用它的对象的 ID,而是提供 null,我收到以下错误消息:
SQLSTATE[23000]: Integrity constraint violation:
1048 Column 'link_id' cannot be null (SQL: insert into 'event_link' ('created_at', 'event_id', 'link_id', 'updated_at') values (2018-06-09 11:27:15, 2, , 2018-06-09 11:27:15))
我已经对我的模型和数据库结构进行了三重检查。
我什至无法想象这个错误是如何发生的,因为 SQL 查询中缺少的 id 是 attach()
方法实际上是对象的 id
被召唤。如果我使用 sync($eventID, false)
而不是 attach()
,结果是一样的。
事件表:
链接表:
事件链接表:
以下是负责存储记录并在 event_link
弱实体中创建条目的 Controller 中有问题的方法。
如果 attach()
行被注释掉,则成功创建了 $link
对象,返回一个链接的 JSON 表示,这证实了这一点(但它缺少'id
' 字段)。
public function store(StoreLink $request) {
$link = Link::create([
'title' => $request->title,
'url' => $request->url,
]);
if ($request['eventId']) {
// $request->eventId is passed successfully, $link id is not passed.
$link->events()->attach($request->eventId);
}
return response()->json($link, 201);
}
链接模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Link extends Model
{
protected $table = 'links';
public $incrementing = false;
public $timestamps = true;
protected $primaryKey = "id";
protected $fillable = ['title', 'url'];
public function events()
{
return $this->belongsToMany('App\Event')->withTimestamps();
}
}
事件模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
protected $table = 'events';
public $incrementing = false;
public $timestamps = true;
protected $primaryKey = "id";
protected $fillable = ['description', 'date', 'image', 'category_id'];
public function category()
{
return $this->belongsTo('App\Event', 'category_id');
}
public function links()
{
return $this->belongsToMany('App\Link', 'event_link')->withTimestamps();
}
public function history()
{
return $this->belongsToMany('App\User', 'user_history');
}
public function favourites()
{
return $this->belongsToMany('App\User', 'user_favourites');
}
}
最佳答案
问题是 public $incrementing = false;
:从两个模型中删除该行。
您的 id
列定义为 AUTO_INCREMENT
,因此 $incrementing
必须为 true
。
关于php - Eloquent Many to Many attach() 正在传递一个空模型 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774229/