访问模型中的子项


Accessing the child in the model

我在两个模型之间有关系。我不想@foreach细读视图中的每个子项,而是想根据条件手动访问每个子项,但不确定如何实现此目的。

父模型代码段

public function childs()
{
    return $this->hasMany('Child');
}

子模型代码段

public function parent()
{
    return $this->belongsTo('Parent');
}

查看刀片.php

@foreach ($parents as $parent)
    @if ($parent->childs()->count() == 2)
        {{ $parent->find(1)->childs()->where('corner', '=', 'A')->first()->id }}
         and
        {{ $parent->find(1)->childs()->where('corner', '=', 'B')->first()->id }}
    @endif
@endforeach 
我想

这样做的原因是因为永远只有 2 个孩子,我想以特定的顺序显示他们,我想把"和"字放在两者之间。

这样,它就会带来表中满足条件的子项总数的第一个结果,而不仅仅是属于我选择的符合条件的父项的孩子。我放first((的原因是因为我得到了多个结果,但实际上只有一个孩子符合条件。

我很确定我把它复杂化了,需要有一种更简单的方法。

感谢您的帮助!!


从穆多纳特的回应来看,这就是我所做的。

父模型代码段

public function childs()
{
    return $this->hasMany('Child');
}

子模型代码段

public function parent()
{
    return $this->belongsTo('Parent');
}
public function scopeCorner($query, $corner)
{
    return $query->whereCorner($corner)->first();
}

查看刀片.php

@foreach ($parents as $parent)
    @if ($parent->childs()->count() == 2)
        {{ $parent->childs()->corner('A')->id }}
        and 
        {{ $parent->childs()->corner('B')->id }}
    @endif
@endforeach 

您可以使用作用域使其更简单一些.http://laravel.com/docs/4.2/eloquent#query-scopes