繁体   English   中英

访问模型中的孩子

[英]Accessing the child in the model

我有两个模型之间的关系。 我不希望通过@foreach仔细浏览视图中的每个子对象,而是要根据条件手动访问每个子对象,但不确定如何实现。

父模型片段

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

子模特片段

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

view.blade.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();
}

view.blade.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM