嘿,我的网站Phones number lookup上的Laravel有问题。我尝试通过联系表选择具有我选择的城市的地方。
我的模型课:
地方类(class):
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 server version for the right syntax to use near 'where
id
= ?)) >= 1' at line 1 (SQL: select * fromplaces
where (select count(*) fromcontacts
wherecontacts
.places_id
=places
.id
andcontacts
= (select * whereid
= 2223)) >= 1)
我知道它缺少“from”
citites
,但是我不知道如何实现。
最佳答案
您有3个使用关系的选项:
1个最简单的解决方案:
Places::whereHas('contacts',function ($q) use ($city_id){
$q->whereHas('cities', function ($q) use ($city_id){
$q->where('id', $city_id);
});
})->get();
2与上面相同,但使用此PR:https://github.com/laravel/framework/pull/4954
Places::whereHas('contacts.cities', function ($q) use ($city_id){
$q->where('id', $city_id);
})->get();
3使用
hasManyThrough
关系:// Place model
public function cities()
{
return $this->hasManyThrough('City', 'Contact');
}
// then
Places::whereHas('cities',function ($q) use ($city_id){
$q->where('cities.id', $city_id);
})->get();
编辑
有了您的架构,很明显,所有建议或原始设置都无法正常工作。
这是一个多对多的关系,在Eloquent中是
belongsToMany
:// Places model
public function cities()
{
return $this->belongsToMany('Cities', 'contacts', 'places_id', 'cities_id')
->withPivot( .. contacts table fields that you need go here.. );
}
// Cities model
public function places()
{
return $this->belongsToMany('Places', 'contacts', 'cities_id', 'places_id')
->withPivot( .. contacts table fields that you need go here.. );
}
然后,您可以像这样调用关系:
$city = Cities::first();
$city->places; // collection of Places models
// contacts data for a single city-place pair
$city->places->first()->pivot->open_hours; // or whatever you include in withPivot above
现在,还有另一种设置方法,以防您还需要
Contacts
模型本身:// Places model
public function contact()
{
return $this->hasOne('Contacts', 'places_id');
}
// Contacts model
public function city()
{
return $this->belongsTo('Cities', 'cities_id');
}
public function place()
{
return $this->belongsTo('Places', 'places_id');
}
// Cities model
public function contact()
{
return $this->hasOne('Contacts', 'cities_id');
}
然后:
$city = Cities::first();
$city->contact; // Contacts model
$city->contact->place; // Places model
hasManyThrough
在这里根本无法使用
关于sql - Laravel Eloquent ORM "whereHas"通过表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25179155/