【问题标题】:Laravel hasManyThrough 2 tablesLaravel hasManyThrough 2 个表
【发布时间】:2017-12-25 12:18:39
【问题描述】:

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

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

我正在尝试检索消息线程 这是行不通的。任何帮助表示赞赏。

【问题讨论】:

  • 这里的线程到底是什么?请详细描述。
  • 线程在某种意义上,向用户发送消息的用户列表。
  • 那么,您想获取所有已向特定用户(接收者)发送消息的用户,并且您获得了该用户的 ID?

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

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

你能检查你的代码吗

【讨论】:

    【解决方案2】:

    您似乎想使用 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');
    
        }
    
    }
    

    Example 来自 laravel 文档

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 2014-09-19
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2021-08-24
      • 2016-07-13
      相关资源
      最近更新 更多