嘿,我和Laravel有问题 . 我尝试通过联系表选择有我选择的城市的地方 .
我的模型类:Places类:
class Places extends Eloquent {
public function contacts()
{
return $this->hasOne('Contacts');
}
public function clubs()
{
return $this->hasOne('Clubs');
}
}
联系人类:
class Contacts extends Eloquent {
public function cities()
{
return $this->hasOne('Cities');
}
}
城市类:
class Cities extends Eloquent {
}
我的查询:
$view->clubs = Places::whereHas('contacts',function ($q) use($city_id){
$q->where('contacts', function ($q) use($city_id){
$q->where('id', $city_id);
});
})->get();
错误消息:
MySQL服务器版本,在第1行的'where id =?))> = 1'附近使用正确的语法(SQL:select * from places where(select count(*)from contacts where contacts.places_id = places.id and contacts =(select * where id = 2223))> = 1)
我知道它缺少"from" citites
但我不知道如何实现它 .
2 回答
您有3个使用关系的选项:
1最直接的解决方案:
2与上述相同,但使用此PR:https://github.com/laravel/framework/pull/4954
3使用
hasManyThrough
关系:编辑
拥有您的架构显然没有任何建议或您的原始设置可以工作 .
这是一个多对多关系,在Eloquent中是
belongsToMany
:然后你可以调用这样的关系:
现在,还有另一种设置方法,如果您还需要
Contacts
模型本身:然后:
hasManyThrough
根本不会在这里工作如您所知,城市ID,您可以从中找到相应的地方,您可以在城市开始并回到这个地方 . 为此,您需要定义关系的倒数 .
现在您可以查询City并找到Place .
EDIT: 在函数中添加了缺失的返回