我有3个表,其中列出了以下字段:
Pricings
-
id
-
route_id
Routes
-
id
-
from_city_id
-
to_city_id
Cities
-
id
-
名字
到目前为止,字段的关系是: pricings belong to a route
和 routes belongs to city
.
但是我不确定这些关系,因为 from_city_id
和 to_city_id
是与 id
id
相关的外键 .
也许我错误地设计我的 table 或其他东西 .
route_id
是 Routes
表上 id
的外键 . from_city_id
和 to_city_id
是 Cities
表上 id
的外键 .
我如何定义这3个表的关系,这样我就可以从pricings模型获得 from city name
和 to city name
,如 $pricing->from_city->name
和 $pricing->to_city->name
?
任何帮助赞赏 .
UPDATE:
我的定价模型:
public function route()
{
return $this->belongsTo(Route::class);
}
我的路线模型:
public function pricing(){
return $this->hasOne(Pricing::class);
}
public function zone(){
return $this->belongsTo(Zone::class);
}
public function city(){
return $this->belongsTo(City::class);
}
public function from_city(){
return $this->belongsTo(City::class);
}
public function to_city(){
return $this->belongsTo(City::class);
}
现在我可以使用 $pricing->route->from_city->name
和 $pricing->route->to_city->name
它显示了正确的结果,但如何使用Laravel实现这一目标?
这是否意味着Laravel将假设 route
表具有字段 to_city_id
和 from_city_id
,因为路由模型中的方法是 to_city()
和 from_city()
?
谢谢
2 回答
一种解决方案可能是进行迁移(新表或更改为现有表) . https://laravel.com/docs/5.3/migrations
Laravel的架构构建非常方便:https://laravel.com/docs/5.0/schema
routes
迁移的一个例子是:php artisan make:迁移路线
}
试试这个:
在定价模型中:
在路线模型中: