2014-10-07 116 views
0

我有這些表:查詢關係

table: investigation 
id 
name 
start_city 
end_city 

table: city 
id 
name 

start_cityend_cityinvestigationcity.id

這是我Investigation型號:

public function start_city(){ 
    return $this->hasOne('City', 'id', 'start_city'); 
} 

public function end_city(){ 
    return $this->hasOne('City', 'id', 'end_city'); 
} 

City型號:

public function start_city(){ 
    return $this->belongsTo('Investigation', 'id', 'start_city'); 
} 

public function end_city(){ 
    return $this->belongsTo('Investigation', 'id', 'end_city'); 
} 

Investigation控制器:

public function show($id){ 
    echo '<pre>'; 
    var_dump(Investigation::find($id)->start_city->name); 
} 

我總是Trying to get property of non-object。我懷疑這種關係有點「破裂」。我該如何解決?我試圖切換hasOnebelongsTo但它不會改變任何東西。注:請不要評論代碼約定,因爲我從其他語言翻譯這個代碼沒有複數形式。

+1

必須用'camelCase'的關係名稱以便使用雄辯的「動態屬性」特徵。 – 2014-10-07 16:56:47

+0

謝謝@JarekTkaczyk,它的工作原理。 :) – shankshera 2014-10-07 17:16:26

回答

0

所有的關係,重命名爲camelCase

public function startCity(){ 
    return $this->hasOne('City', 'id', 'start_city'); 
} 

public function endCity(){ 
    return $this->hasOne('City', 'id', 'end_city'); 
} 

,並同所有其他型號。

然後你可以使用dynamic properties象下面這樣:

$investigation->startCity; 

,否則你不能使用動態屬性,你會需要這樣的:

$investigation->start_city()->getResults()->name;