Laravel 5.1 - 雄辩的关系
问题描述:
我是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
任何一个可以请给我解释一下我在做什么错在这里,妥善如何工作?
答
尝试->first()
而不是get()
。 get()
返回数组。或者在测试模型中使用protected $primaryKey = 'test_id';
,然后->find($id)
尝试使用 - > first()而不是get()。 get()返回数组。或者使用protected $ primaryKey ='test_id';在测试模型,然后找到(编号) –
你可以描述两个表模式吗? –
@TimvanUum,帮助了很多。 :) –