我有两个表如下:用户表:
|id|name|email|password|created_at|updated_at
表消息:
|id|sender_id|receiver_id|message|created_at|updated_at
用户模型:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
我正在尝试检索无法正常工作的消息线程。任何帮助赞赏。
您似乎想要使用hasMany关系检索属于单个线程(用户列表)的所有消息通过User
模型,要做到这一点您必须在线程模型中定义hasManyThrough
而不是在User
模型中,这是一个示例:
用户:
|id|name|email|password|created_at|updated_at|thread_id
注意thread_id
外键,因为线程是用户列表
线:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
来自laravel doc的Example
这是laravel eloquent relationship的一个例子
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
你能查看你的代码吗?