Laravel hasManyThrough 2表

问题描述 投票:2回答:2

我有两个表如下:用户表:

|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');
}

我正在尝试检索无法正常工作的消息线程。任何帮助赞赏。

php mysql laravel laravel-5 eloquent
2个回答
1
投票

您似乎想要使用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


0
投票

这是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...
        );
    }
}

你能查看你的代码吗?

© www.soinside.com 2019 - 2024. All rights reserved.