dongpao1083 2017-01-13 15:45
浏览 251
已采纳

两个表之间的Laravel关系有两个外键

Hey how can I make relationships between two table.

Users: id, email
Notification: id, user_id(id of the logged user), client_id(id of sender)

I would like make relationship between users and notifications by user_id and client_id. Then I will can get all notifications assigned to logged user, and get email of sender users.

I made that:

    public function notifications_with_client() {
    return $this->hasManyThrough('App\Models\User', 'App\Models\Notification', 'user_id', 'id', 'client_id');
}

But when I using query i got good notifications but with wrong email. I got email from ralationship id(from users table) == id(from notifications table)

My query

$column = 'notifications_with_client';
$value[1] = ['email', 'notifications.id', 'client_id'];
$query->with([$column => function($query) use ($value) {
                      $query->select($value[1]);
                  }]);

Someone know what I do wrong?

  • 写回答

3条回答 默认 最新

  • dongpu2694 2017-01-13 16:25
    关注

    You can try it by defining the following relations:

    User Model

    public function notifications()
    {
        return $this->hasMany('App\Models\Notification');
    }
    

    Notification Model

    public function to()
    {
      return $this->belongsTo('App\Models\User', 'user_id');
    }
    
    public function from()
    {
      return $this->belongsTo('App\Models\User', 'client_id');
    }
    

    And then you can query it as:

    $notifications = auth()->user()->notifications()->with('from')->get();
    

    Or if you just want email then query it as:

    $notifications = auth()->user()
                        ->notifications()
                        ->with(['from' => function($q) {
                            $q->select('email');
                        }])
                        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥200 比特币ord程序wallet_constructor.rs文件支持一次性铸造1000个代币,并将它们分配到40个UTXO上(每个UTXO上分配25个代币),并设置找零地址
  • ¥15 关于Java的学习问题
  • ¥15 如何使用chatgpt完成文本分类任务?
  • ¥15 已知速度v关于位置s的等式,怎么转化为已知位置求速度v的等式
  • ¥15 我有个餐饮系统,用wampserver把环境配置好了,但是后端的网页却进去,是为什么,能不能帮远程一下?
  • ¥15 R运行没有名称为"species"的插槽对于此对象类"SDMmodelCV"
  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码