我有以下表格:
Makes:
id - make_name
Models:
id - model_name - make_id
Trims:
id - trim_name - model_id
Forsale_Cars:
id - trim_id - year - price我的问题是,如果用户选择(Make ),我如何返回Forsale_Cars表中列出的所有trims?
发布于 2014-05-30 18:32:46
以雄辩的口才来说,这将适用于你:
$make = Make::find($selectedId);
$trims = $make->trims()->has('forsales')->get();
// returns collection of Trim models that have related row in foresale_cars
// to also load the forsales models you can then do this (load on the collection):
$trims->load('forsales');
// or instead in one chain
$trims = $make->trims()->has('forsales')->with('forsales')->get();您需要在Make模型上建立这种关系:
public function trims()
{
return $this->hasManyThrough('Trim', 'Model');
}其他关系,如你之前的问题,MySQL relation with multiple tables
发布于 2014-05-30 18:23:14
你想给我看看。所以从trims中选择。您只想显示Forsale_Cars中存在的trims,所以使用存在(或者IN,如果您想成组的话)。你只想展示某些产品的装饰。再次使用EXISTS (或IN),因为您可以这样说:哪里存在带有指定make的模型(或者模型在该make的模型集合中)。
希望这能有所帮助。否则就带着你的东西回来,这样我们就能给你更多的建议。
发布于 2014-05-30 18:23:53
在所有表之间进行连接,如下所示,这将使您获得匹配的行
select m.id as makeId,
t.id as trimid,
t.trim_name,
t.model_id
from Makes m
inner join Models mo
on m.id = mo.make_id
inner join Trims t
on t.model_id = mo.id
inner join Forsale_Cars fc
on fc.trim_id = t.idhttps://stackoverflow.com/questions/23960953
复制相似问题