我对php中的laravel和OOP是个新手。我正在尝试迭代雄辩的对象,但我想我没有好的方法。
例如: Categorie Model:
class Categorie extends Eloquent {
protected $table = 'categorie';
protected $timestamp = true;
protected $fillable = array('id_parent');
public function children() {
return $this->hasMany('Categorie','id_parent','id');
}
public function traduction() {
return $this->hasMany('Categorie_Langue','id_categorie','id');
}
}控制器索引:
public function index()
{
$categorie = Categorie::
whereNull('id_parent')
->has('traduction')
->with('traduction')
->get()
;
return ($categorie);
}返回如下内容:
[{"id":3,"id_parent":null,"created_at":"2014-08-08 07:04:57","updated_at":"2014-08-08 07:04:57","deleted_at":null,"traduction":[{"id":1,"id_categorie":3,"id_langue":1,"nom":"MEUBLES"}]},{"id":4,"id_parent":null,"created_at":"2014-08-08 07:07:05","updated_at":"2014-08-08 07:07:05","deleted_at":null,"traduction":[{"id":2,"id_categorie":4,"id_langue":1,"nom":"MEUBLES"}]},{"id":6,"id_parent":null,"created_at":"2014-08-08 11:27:11","updated_at":"2014-08-08 11:27:11","deleted_at":null,"traduction":[{"id":4,"id_categorie":6,"id_langue":1,"nom":"DECORATIONS"}]}]
这正是我所需要的,但我想直接访问像这样的诱骗;
echo $categorie->traduction->nom;但是我得到了这个错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$traduction如何在面向对象中使用诱导式遍历类别,我可以用foreach在foreach中实现,但似乎不是最好的实践?
谢谢你的帮助
发布于 2014-08-09 06:07:19
尝试: echo $categorie->traduction->lists('nom');
希望它能有所帮助!G
发布于 2014-08-09 17:47:57
你想得到类别的导引,其中(“parent_id”,"=",NULL);对吗?
那么你应该能够做到这一点
$categories = Categorie::all();
foreach($categories as $category)
{
$categories->load(array('traduction'=>function($q){
$q->where('Categorie.parent_id', NULL);
}))
}
return $traductions;您也可以尝试使用with
return Categorie::with(array('traduction'=>function($q){
$q->where('Categorie.parent_id', NULL);
}))->get();在尝试这些之后发布你的结果..
https://stackoverflow.com/questions/25210088
复制相似问题