with()与条件的关系检索所有记录-Laravel

时间:2018-10-18 08:37:07

标签: laravel-5 eloquent

我只想检索列出的组织,但是数据库返回所有记录。

您可以看到下面的记录不应该作为列出的组织返回,我在代码,我的模型和从数据库中得到的结果下面包括了该列

      $organisations = Organisation::with(['year_status' => function ($query) use ($year_id) {
                    $query->where(['year_id' => $year_id, 'is_listed' => 1]);
                }])->get();



public function year_status()
    {
        return $this->hasMany('App\OrganisationYearStatus');
    } 

 and what I got :

11 => Organisation {#630 ▼
      #fillable: array:8 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:14 [▼
        "id" => 39
        "organisation" => "Test Organisation"
        "sector_id" => 1
        "country_id" => 1
         ]
      #original: array:14 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "year_status" => Collection {#632 ▼
          #items: []
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }

数据库结构:

id  
organisation_id
year_id
is_listed

1 个答案:

答案 0 :(得分:0)

确保您的关系建立良好(组织模型具有“ many year_status”),并且您的字段在YearStatus模型中的可见数组中。

此外,您正在使用的查询被翻译为:

SELECT * FROM organizations where exists 
  (select * from year_status where organizaton_id = organizations.id 
   and year_id = $year_id and is_listed = 1)

它不会获取数据库中存在的所有记录,而是由于关系和您添加的字段而获取

注意:如果只想获取具有OrganizationYearStatus的组织,则应使用:

Organisation::whenHas('year_status' => function ($advancedWhenHas) use ($year_id) { 
  $advancedWhenHas->with(['year_status' => function ($query) use ($year_id) {
                    $query->where(['year_id' => $year_id, 'is_listed' => 1]);
}}])->get();

您可以输入->toSql()而不是->get(),以确保查询符合您的要求