class Ingredient extends Eloquent {
public function unit() {
return $this->hasOne('IngredientUnit', 'id', 'unit_id');
}
}
class IngredientUnit extends Eloquent {
public function ingredient() {
return $this->belongsTo('Ingredient', 'unit_id', 'id');
}
public function getNamesAttribute() {
$quantity = $this->ingredient()->quantity; // <- ErrorException
...
}
}
ErrorException(E_UNKNOWN):
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$quantity
如果我删除括号 - $this->ingredient->quantity;
- 我会
ErrorException(E_UNKNOWN)
Trying to get property of non-object
如何获取关系对象的属性(belongsTo)?
架构:
Schema::create('ingredients', function(Blueprint $table)
{
$table->increments('id');
$table->integer('recipe_id')->unsigned();
$table->integer('unit_id')->unsigned()->nullable();
$table->float('quantity')->unsigned();
...
});
Schema::create('ingredient_units', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
...
});
答案 0 :(得分:2)
使用这些表格,你的关系是错误的。
你需要交换它们,因为它是这样的:unit hasOne/hasMany ingredients
,ingredient belongsTo unit
。
// Ingredient
public function unit()
{
return $this->belongsTo('IngredientUnit', 'unit_id', 'id');
}
// IngredientUnit - I don't think it's hasOne, rather hasMany
public function ingredients()
{
return $this->hasMany('Ingredient', 'unit_id', 'id');
}
接下来,这无效:
$this->ingredient()->quantity;
但只要从关系中返回模型,这将有效:
$this->ingredient->quantity;
所以基本上你没有相关的成分,这就是为什么它返回null
并且你得到了错误。
答案 1 :(得分:0)
首先你应该改变:
$quantity = $this->ingredient()->quantity;
到
$quantity = $this->ingredient->quantity;
但是如果没有找到成分,你就会遇到异常,所以最好把它改成:
$ingredient = $this->ingredient;
$quantity = ($ingredient) ? $ingredient->quantity : 0;
如果没有找到成分,分配0
;