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