0
我在我的應用程序下表:Laravel嘗試查詢relatinship模型的hasMany
projects
projects_plot_types
項目可以有很多的情節類型。我在項目模型中設置了以下關係。
/**
* The plot types that belong to the project.
*
* @return Object
*/
public function plotTypes()
{
return $this->hasMany('App\Models\Project\ProjectsPlotTypes');
}
我希望能夠通過查詢它是在項目型號,以得到情節類型。
我已經試過這一點,但它不工作:
$project->with('plotTypes')->whereHas('plotTypes', function ($query) use ($row) {
$query->where('name', $row->plot_name);
})->first()->plotTypes->first()->id;
有人能指出我在正確的方向?
的$result
按照下面的評論的輸出是:
Project {#705 ▼
#table: "projects"
#fillable: array:7 [▶]
+timestamps: true
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:10 [▶]
#original: array:10 [▶]
#relations: array:1 [▼
"plotTypes" => Collection {#769 ▼
#items: array:1 [▼
0 => ProjectsPlotTypes {#774 ▼
#table: "projects_plot_types"
#fillable: array:2 [▶]
+timestamps: false
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:4 [▼
"id" => "2"
"project_id" => "1"
"name" => "TYPE 3 - VENTILATION"
"budget" => "245.69"
]
#original: array:4 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
謝謝,但我怎麼然後訪問plotTypes ID? '$ result-> id'會打印項目ID大概? – V4n1ll4
'$ result-> plotTypes() - > first() - > id'應該得到它你正在尋找的。 –
這段代碼似乎仍然沒有獲取我需要的行。 – V4n1ll4