Laravel 如何定义这个hasManyThrough关系?
我有以下几种型号。事件属于案例文件。案例文件和用户是多对多的Laravel 如何定义这个hasManyThrough关系?,laravel,eloquent,Laravel,Eloquent,我有以下几种型号。事件属于案例文件。案例文件和用户是多对多的 class Casefile extends Model { public function users() { return $this->belongsToMany(User::class)->withTimestamps(); } public function events() { return $this->morphMany('Ap
class Casefile extends Model
{
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
public function events()
{
return $this->morphMany('App\Event', 'casefile');
}
}
class User extends Authenticatable
{
public function casefiles()
{
return $this->belongsToMany(Casefile::class)->withTimestamps();
}
}
class Event extends Model
{
public function casefile()
{
return $this->belongsTo('App\Casefile');
}
public function users()
{
return $this->hasManyThrough('App\User', 'App\Casefile');
}
}
当我尝试:
App\Event::find(526)->users()->get();
它给出:
带有消息“SQLSTATE[42S22]”的/Database/QueryException:
未找到列:1054字段中的未知列“casefiles.event_id”
列出“SQL:选择用户。*,casefiles.event\u id from users”
casefiles.id=users.casefile\u id上的内部联接casefiles
其中casefiles.event_id=526'
如何通过Casefile定义事件具有多个用户关系?如果列名未遵循laravel命名约定。然后可以像这样指定列名
public function users()
{
return $this->hasManyThrough(
'App\User',
'App\Casefile',
'event_id', // Foreign key on casefiles table...
'user_id', // Foreign key on users table...
);
}
有关更多信息,如果没有casefile\u用户表的透视模型,则无法在此处使用HasManyThrough
您可以改为定义归属关系:
公共功能用户
{
返回$this->belongsToMany'App\User'、'casefile\u User'、'casefile\u id',null'casefile\u id';
}
Casefile类上events方法中的morphMany是故意的吗?它看起来是错误的,可能会导致您的错误。事件中的许多变体都是经过设计的。但是,我尝试将其更改为hasMany,并得到相同的错误。