Pio*_*nek 8 sql orm laravel eloquent
嘿,我和Laravel有问题.我尝试通过联系表选择有我选择的城市的地方.
我的模型类:Places类:
class Places extends Eloquent {
public function contacts()
{
return $this->hasOne('Contacts');
}
public function clubs()
{
return $this->hasOne('Clubs');
}
}
Run Code Online (Sandbox Code Playgroud)
联系人类:
class Contacts extends Eloquent {
public function cities()
{
return $this->hasOne('Cities');
}
}
Run Code Online (Sandbox Code Playgroud)
城市类:
class Cities extends Eloquent {
}
Run Code Online (Sandbox Code Playgroud)
我的查询:
$view->clubs = Places::whereHas('contacts',function ($q) use($city_id){
$q->where('contacts', function ($q) use($city_id){
$q->where('id', $city_id);
});
})->get();
Run Code Online (Sandbox Code Playgroud)
错误消息:
MySQL服务器版本使用附近的正确的语法'其中
id=))> = 1?'在1号线(SQL:SELECT*FROMplaces其中(SELECT COUNT(*)从contacts哪里contacts.places_id=places.id和contacts=(选择*其中id= 2223) )> = 1)
我知道它缺少"来自",citites但我不知道如何实现它.

Jar*_*zyk 15
您有3个使用关系的选项:
1最直接的解决方案:
Places::whereHas('contacts',function ($q) use ($city_id){
$q->whereHas('cities', function ($q) use ($city_id){
$q->where('id', $city_id);
});
})->get();
Run Code Online (Sandbox Code Playgroud)
2与上述相同,但使用此PR:https://github.com/laravel/framework/pull/4954
Places::whereHas('contacts.cities', function ($q) use ($city_id){
$q->where('id', $city_id);
})->get();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
拥有您的架构显然没有任何建议或您的原始设置可以工作.
这是一个多对多关系,在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.. );
}
Run Code Online (Sandbox Code Playgroud)
然后你可以调用这样的关系:
$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
Run Code Online (Sandbox Code Playgroud)
现在,还有另一种设置方法,以防您需要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');
}
Run Code Online (Sandbox Code Playgroud)
然后:
$city = Cities::first();
$city->contact; // Contacts model
$city->contact->place; // Places model
Run Code Online (Sandbox Code Playgroud)
hasManyThrough 根本不会在这里工作