繁体   English   中英

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

[英]Laravel relationship between two tables with two foreign keys

嘿,我该如何在两个表之间建立关系。

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

我想通过user_id和client_id在用户和通知之间建立关系。 然后,我将获得分配给已登录用户的所有通知,并获取发送者用户的电子邮件。

我做到了:

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

但是,当我使用查询时,我收到了很好的通知,但电子邮件错误。 我收到了劳资关系ID(来自用户表)== ID(来自通知表)的电子邮件

我的查询

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

有人知道我做错了吗?

您可以通过定义以下关系来进行尝试:

User模型

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

Notification模型

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

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

然后您可以查询为:

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

或者,如果您只想要email则查询为:

$notifications = auth()->user()
                    ->notifications()
                    ->with(['from' => function($q) {
                        $q->select('email');
                    }])
                    ->get();
public function user()
{
    return $this->belongsTo(Users::class, 'user_id');
}

public function client()
{
    return $this->belongsTo(Users::class, 'client_id');
}

在通知模型中使用此代码,您可以使用

$this->user(); // $notification->user();

和发件人

$this->client(); //$notification->client();

您不能使用$this->hasManyThrough(). 它有不同的用途

您可以像这样使用$this->belongsTo()

class User extends BaseModel
{
    public function user()
    {
        return $this->belongsTo(Notification::class, 'user_id');
    }

    public function client()
    {
        return $this->belongsTo(Notification::class, 'client_id');
    }
}

然后,您可以像查询。

User::with(['user']);

要么

User::with(['client']);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM