根据条件使用 Eloquent 和 return 结果访问数据透视列 - Laravel、Eloquent

Access Pivot column using Eloquent and return result as per the condition - Laravel, Eloquent

我有如下所示格式的数据,它是多对多关系。

我只想从 relation2 中检索其值为 pivot (is_column1 = 0) 的那些条目。如何以 eloquent 样式访问数据透视表?

查询

$data = Relation1::with(['relation2' => function ($query){
    $query->where('col4', '1');
    $query->where('pivot.is_column1', '1'); // I want something like this
}])->get();

结果

[
  {
     "id": 1,
     "name": "Test",
     "relation2": 
        [
          {
             "id": 3,
             "col2_id": 1,
             "col3_id": 1,
             "col4": "1",
             "pivot": {
                 "col1_id": 1,
                 "col2_id": 2,
                 "is_column1": "1"
              }
           }
        ] 
     }
 ]

使用wherePivot()方法:

Relation1::with(['relation2' => function ($query) {
    $query->where('col4', '1')
        ->wherePivot('is_column1', '1');
}])
->get();

如果你有连接两个 table 的枢轴 table 就容易多了(尤其是 many-to-many 关系)。我建议您创建一个枢轴 table,其中 table 名称必须按字母顺序排列在 table 之间(最好的方法是为此创建一个迁移)。

例如,如果您有用户和标签,数据透视表 table 必须为单数形式

user_tag

user_tag table 必须有 user_idtag_id 列可用。

然后按照User.php的思路,做一个Laravel可以理解为属性

的函数
public function tags() {
    $this->belongsToMany(Tag::class);
}

反之亦然。声明模型之间的关系后,Laravel 会自动查看 user_tag table(确保按字母顺序排列,否则将不起作用)。

您可以像这样做一些事情:

$user->tags; // returns all tag records in database associated in the pivot table $tag->users; // returns all users associated with tag

这样做你可以通过关系访问用户或标签的属性

$user->tags()->pluck('name');

类似的东西