Laravel 5.1 - Eloquent 关系
Laravel 5.1 - Eloquent Relationships
我是 Laravel 的新手。我正在查看 Eloquent 关系。我遵循文档并将我的一对多关系定义为:
// 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 的惯例。所以如果我在 Tinker 中这样做:
$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()
returns 数组。或者在测试模型中使用 protected $primaryKey = 'test_id';
然后 ->find($id)
我是 Laravel 的新手。我正在查看 Eloquent 关系。我遵循文档并将我的一对多关系定义为:
// 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 的惯例。所以如果我在 Tinker 中这样做:
$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()
returns 数组。或者在测试模型中使用 protected $primaryKey = 'test_id';
然后 ->find($id)