在Laravel 4中加载资源时加载模型变量


Load model variables when eager loading resources in Laravel 4

我从一个REST API返回JSON数据,在这个API中我渴望加载相关模型(在本例中是资源)。

// In my controller (FooController.php)
public function show($id)
{
  return Foo::with('bar')->find($id);
}
// In my model (Bar.php)
class Bar extends Eloquent {
  public $baz = 1;
  public function foo()
  {
    return $this->belongsTo('Foo');
  }
}

我怎么能也返回$baz,而使用with('bar')和保持对象关系?我可以在我的视图/控制器中使用$foo->baz ?

之类的东西。

使用访问器应该能够做到这一点。由于$baz不是一个实际的模型属性(好吧,我假设您的问题就是这种情况),您可以执行以下操作:

public function getBaz()
{
  return $this->baz;
}

>