我正在开发一个应用程序使用laravel和雄辩的orm,它使用一个充满事件信息的数据库。
我已成功实施 attach()
在我的用户和角色模型的相关控制器中。
我的事件模型可以有很多链接。一个链接可以有许多事件。我的问题是 attach()
没有提供正在调用的对象的id,而是提供null,我收到以下错误消息:
sqlstate[23000]:完整性约束冲突:
1048列“link\u id”不能为空(sql:插入到“event\u link”(“created\u at”,“event\u id”,“link\u id”,“updated\u at”)值中(2018-06-09 11:27:15,22018-06-09 11:27:15))
我已经检查了我的模型和数据库结构。
我甚至无法想象这个错误是怎么发生的,因为sql查询中缺少的id是 id
那个 attach()
方法实际上正在被调用。如果我使用 sync($eventID, false)
而不是 attach()
,结果相同。
事件表:
链接表:
事件链接表:
下面是负责存储记录并在 event_link
弱小的实体。
这个 $link
如果 attach()
行被注解掉,返回一个链接的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');
}
}
1条答案
按热度按时间irtuqstp1#
问题是
public $incrementing = false;
:从两个模型中删除行。你的
id
列定义为AUTO_INCREMENT
,所以$incrementing
必须是true
.