簡體   English   中英

Laravel 5僅選擇hasMany關系上的關系數據

[英]Laravel 5 select only relationship data on hasMany relationship

我正在構建一個具有projects並且項目具有plot_types的應用程序。

我希望能夠檢查當前項目下是否存在plot_type。

我有以下代碼:

$testResult = $project->with(['plotTypes' => function($query) use ($row) {
            $query->where('name', $row->plot_name);
        }])->first()

這將產生以下MySQL:

select exists(select * from `projects` where exists (select * from `projects_plot_types` where `projects_plot_types`.`project_id` = `projects`.`id` and `name` = ?)) as `exists`

該SQL返回與$project對象無關的行。 例如,當我做dd($project)我得到:

#attributes: array:11 [▼
    "id" => "4"
    "name" => "xxx"
    "number" => "1234"
    "builder" => "1"
    "overall_budget" => "3456.00"
    "start_date" => "2016-03-31"
    "end_date" => "2016-04-30"
    "created_date" => "2016-03-16 15:22:05"
    "updated_date" => "2016-03-16 15:22:07"
  ]

然而,當我做dd($testResult); 它給;

#relations: array:1 [▼
"plotTypes" => Collection {#767 ▼
  #items: array:1 [▼
    0 => ProjectsPlotTypes {#770 ▼
      #table: "projects_plot_types"
      #fillable: array:2 [▶]
      +timestamps: false
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      #attributes: array:4 [▼
        "id" => "1"
        "project_id" => "1"
        "name" => "TYPE 1  - VENTILATION"
        "budget" => "324.67"
      ]

注意,上面的project_id顯示為1 這與當前項目無關,因為當前項目ID為4

為什么會這樣呢?

這是ActiveRecord模型中那些可能造成混淆的部分之一。 您所有的模型實例都包含用於檢索模型實例的相同方法,因此,很容易想到某些事情在實際上不起作用時應該以一種方式起作用。

調用$project->with() ,與調用Project::with()完全相同。 即使您在項目的實例上調用with() ,也不會將加載的對象限制為僅與實例相關的對象。

調用$project->with() ,它首先要做的是為所有項目創建一個新查詢,然后添加急切的加載。 然后,您調用first() ,它僅獲取第一個項目記錄及其所有渴望加載的對象。

要獲得特定項目的圖類型,您有兩種選擇。

  1. 只是查詢關系。 $project->plotTypes()為您提供與項目關聯的所有繪圖類型的基本查詢。 您可以添加約束並從那里獲取記錄。

     $plotTypes = $project->plotTypes()->where('name', $row->plot_name)->get(); dd($plotTypes); 
  2. 使用約束加載相關的圖類型:

     // assume your project doesn't have any plottypes loaded yet $project = Project::find(1); // load the plottypes relation with constraints $project->load(['plotTypes' => function($query) use ($row) { $query->where('name', $row->plot_name); }]); dd($project->plotTypes); 
  3. 過濾已加載的相關圖類型的Collection $project->plotTypes具有與項目相關的所有繪圖類型,但是您可以使用Collection上的where()方法where()與查詢中的where()不同)來過濾Collection的記錄。

     // assume your project already has all plotTypes loaded $project = Project::with('plotTypes')->find(1); // you just want to get a subset of those pre-loaded plottypes $plotTypes = $project->plotTypes->where('name', $row->plot_name); dd($plotTypes); 

使用whereHas方法而不是with進行過濾

$testResult = $project->whereHas('plotTypes' => function($query) use ($row) {
        $query->where('name', $row->plot_name);
 })->with('plotTypes')->first();

而且,您要獲取所有相關記錄還是僅獲取第一條記錄?

如果全部,然后將first()更改為get()

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM