2016-02-12 182 views
1

情景 - 我有3個表>國家,州,市。市有州立專欄,州有國家專欄,國家沒有參考。Laravel 5 - 雄辯模型 - 系列3表

城市模型方法

public function state(){ 
    return $this->belongsTo('App\State', 'stateid'); 
} 

國家示範性方法

public function country(){ 
    return $this->belongsTo('App\Country', 'countryid'); 
} 
public function cities(){ 
    return $this->hasMany('App\City', 'stateid'); 
} 

國家示範方法

public function states() 
{ 
    return $this->hasMany('App\State', 'countryid'); 
} 

問題 - 我想在一個國家的城市名單。我如何在這樣的國家模式中創建一個方法? -

public function cities(){ 
    return $this->states()->cities(); //Calling hasMany on builder is not possible. 
} 

同樣,從城市模型的國家名稱的方法。

+1

你要找因爲是'hasManyThrough()'。請參閱:https://laravel.com/docs/5.1/eloquent-relationships#has-many-through – Mysteryos

+0

@Mysteryos - 謝謝,工作。 – asachanfbd

+0

@Mysteryos - 有沒有辦法從城市中獲取國家? – asachanfbd

回答

0

若要檢索與一個國家的所有城市的集合,使用hasManyThrough方法:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Country extends Model 
{ 
    public $timestamps = false; 

    public function states() 
    { 
     return $this->hasMany(State::class); 
    } 

    public function cities() 
    { 
     return $this->hasManyThrough(City::class, State::class); 
    } 
} 
0

國家型號:

<?php 

    namespace App; 
    use Illuminate\Database\Eloquent\Model; 

    class Country_master extends Model 
    {  

     public function city_state_data() 
     { 
      return $this->belongsToMany('App\State_master','city_masters'); 
     } 
    } 

呼叫模型:

<?php 
    $data=Country_master::find(1)->city_state_data()->select('city_name','state_name')->get();