我是laravel的新手,必须为3个表定义关系。表格是事件,类别,包。
事件可以有多个类别,每个类别可以有多个包。相同的类别可以在各种事件中。
到目前为止,我有以下表格,但不确定我是否采取了正确的方法:
Table:events
id - int
title - varchar ...
Table: categories
id - int
name - varchar
Table:packages
id - int
name - varchar
price - decimal
Table:category_package
category_id - int
package_id - int
Table:event_package
event_id - int
package_id - int
内包装模型我有:
public function categories()
{
return $this->belongsToMany('\App\Category');
}
public function events()
{
return $this->belongsToMany('\App\Event');
}
内部事件和类别模型我有:
public function packages()
{
return $this->belongsToMany('\App\Package');
}
当我查询特定事件及其关系时,我想得到以下结果:
[
"events" => [
"id" => 1,
"title" => "whatever title",
"categories" => [
[
"id" => 1,
"name" => "the category",
"packages" => [
["id" => 1, "name" => "pack1"],
["id" => 2, "name" => "pack2"],
["id" => 3, "name" => "pack3"]
]],
[
"id" => 2,
"name" => "second cat",
"packages" => [
["id" => 4, "name" => "pack4"],
["id" => 5, "name" => "pack5"],
["id" => 6, "name" => "pack6"]
]],
]
]
]
这是否可能在laravel中,我将如何去做。我很确定我没有采取正确的方法。
由于
答案 0 :(得分:1)
根据您的表格结构和评论,您似乎想要进行此设置:
Event
有多个Packages
Package
属于一个Event
Category
有多个Packages
Package
属于一个Category
您不需要数据透视表(category_package
和event_package
),因此请删除它们。然后,您的packages
表格需要添加event_id
和category_id
字段。
Table:packages
id - int
name - varchar
price - decimal
event_id - int
category_id - int
您应该像这样设置模型:
class Event extends Model {
public function packages() {
return $this->hasMany('App\Package');
}
}
class Category extends Model {
public function packages() {
return $this->hasMany('App\Package');
}
}
class Package extends Model {
public function event() {
return $this->belongsTo('App\Event');
}
public function category() {
return $this->belongsTo('App\Category');
}
}
你想要在你的问题中得到的数组不能被优雅地检索,你必须做一些手工工作,但如果你使用eager loading with constraints就不难
要获得一个Event
及其Categories
和Packages
,您可以这样做:
$event = Event::find($eventId); // Or however you want to get the Event
$event['categories'] = Category::with(['packages' => function($query) use($event) {
$query->where('event_id', $event->id);
}])->get();
要获得多个Events
及其Categories
和Packages
,您只需使用循环并为每个Event
添加类别。
$events = Event::all(); // Or however you want to get the Events
foreach ($events as $key => $event) {
$events[$key]['categories'] = Category::with(['packages' => function($query) use ($event) {
$query->where('event_id', $event->id);
}])->get();
}