2015-12-03 201 views
0

我是Laravel的新手。我在看着雄辯的關係。我遵循文檔,並將我的一對多關係定義爲:Laravel 5.1 - 雄辯的關係

// in the test model 
public function questions() 
    { 
     return $this->hasMany('App\Question', 'test_name_id', 'test_id'); 
    } 
// in the question model 
public function test() 
    { 
     return $this->belongsTo('App\Test', 'test_name_id', 'test_id'); 
    } 

請注意,我沒有按照慣例命名id。所以如果我在修補匠中這樣做:

$test = App\Test::first(); 
$question = $test->questions; 

它工作正常。但是,如果要記錄比第一像做任何其他:

$test = App\Test::where(['test_id'=>'2'])->get(); 
$question = $test->questions; 

它給我這個錯誤:

PHP error: Trying to get property of non-object on line 1 

任何一個可以請給我解釋一下我在做什麼錯在這裏,妥善如何工作?

+1

嘗試使用 - > first()而不是get()。 get()返回數組。或者使用protected $ primaryKey ='test_id';在測試模型,然後找到(編號) –

+0

你可以描述兩個表模式嗎? –

+0

@TimvanUum,幫助了很多。 :) –

回答

1

嘗試->first()而不是get()get()返回數組。或者在測試模型中使用protected $primaryKey = 'test_id';,然後->find($id)