【发布时间】:2020-06-30 12:11:45
【问题描述】:
我使用 Laravel 7.2,我有 2 个模型:
用户
public function orders()
{
if($this->hasRole("seller")) {
return $this->hasMany('App\Models\Order', 'seller_id', 'id');
} else if($this->hasRole("client")) {
return $this->hasMany('App\Models\Order', 'user_id', 'id');
}
}
订购
迁移:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->boolean('status')->default(false);
$table->text('description')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->unsignedBigInteger('seller_id');
$table->foreign('seller_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
代码:
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function seller()
{
return $this->belongsTo('App\Models\User', 'seller_id');
}
现在在我的例子中,用户有两个角色 seller 或 client。但是当我尝试获取用户订单时,laravel 会返回错误消息:
在 null 时调用成员函数 addEagerConstraints()
或者当我尝试获取自定义订单用户或卖家相关数据时,也会返回相同的错误消息。
我有什么错误或我错误地创建了关系?
【问题讨论】:
-
首先,您的迁移文件中有错误。
$table->id();应该是$table->bigIncrements('id'); -
从您的评论来看,假设您使用的是旧版本的框架。 @MuktiRaniGhosh
-
你是对的。我没有注意到您使用的是 Laravel 7.2。对不起
标签: laravel eloquent foreign-keys relationship laravel-7