【问题标题】:Laravel relationship between two tables with two foreign keys具有两个外键的两个表之间的 Laravel 关系
【发布时间】:2017-01-13 15:45:05
【问题描述】:

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

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

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

【问题讨论】:

  • 我认为你需要建立多对多关系?
  • 如果你能发布你有这种关系的模型会非常有帮助。client_id 引用了什么?我假设用户。如果是这样,那么您确实具有多对多关系。
  • 这里不能使用$this->hasManyThrough(),请使用$this->belongesTo(),正如我在下面的回答中提到的那样

标签: php postgresql laravel eloquent psql


【解决方案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();

【讨论】:

    【解决方案2】:
    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();
    

    【讨论】:

      【解决方案3】:

      您不能使用$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');
          }
      }
      

      然后就可以查询like了。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-27
        • 2017-07-31
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 2017-12-13
        • 2022-01-09
        • 2020-10-13
        相关资源
        最近更新 更多