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

Laravel relationship between two tables with two foreign keys

嘿,我怎样才能在两个 table 之间建立关系。

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

但是当我使用查询时,我收到了很好的通知,但是电子邮件有误。 我收到了来自 ralationship id(from users table) == id(from notifications table)

的邮件

我的查询

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

有人知道我做错了什么吗?

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(). 它用于 different reason

你可以这样使用$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']);

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

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();