Я создаю приложение, которое имеет projects
и проекты имеют plot_types
.Laravel 5 выбрать только данные отношений по hasMany отношения
Я хочу, чтобы проверить, существует ли объект 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
. Это не связано с текущим проектом, поскольку текущий идентификатор проекта равен 4
.
Почему это происходит?
Великолепный ответ, большое вам спасибо! – V4n1ll4