du13520157325 2014-04-25 16:53
浏览 94
已采纳

Laravel对象关系在foreach循环中不起作用

I have a typical model relation. I have the model QR, which hasMany Rating, and a Model Rating, which belongsTo Qr.

Now I want to output the Ratings, which belong to a single qr model, through a foreach loop like this:

            <table>
                <tr>
                    <th>ID</th>
                    <th>UnitID</th>
                    <th># of Ratings</th>
                </tr>

                @foreach($qrs as $qr->ratings)

                <tr>
                    <td>{{$qr->id}}</td>
                    <td>{{$qr->unit_id}}</td>
                    <td>{{$qr->ratings->count()}}</td>
                </tr>

                @endforeach
            </table>

This is my Controller:

public function index()
{
    //
    $unit = Unit::all()->first();
    $qrs = Qr::all()->first();
    return View::make('index')
        ->with('unit', $unit)
        ->with('qrs', $qrs);
}

Here are my two Models

Rating.php:

    class Rating extends \Eloquent {
    protected $guarded = [];

    public function qr(){
        return $this->belongsTo('Qr');
    }
}

Qr.php:

    class Qr extends \Eloquent {
    protected $guarded = [];

    public function unit(){
        return $this->belongsTo('Unit');
    }

    public function ratings(){
        return $this->hasMany('Rating');
    }
}

I actually want to output the count of ratings, a Qr-Code has. I know it is possible to do it somehow like this:

 {{Rating::where('qr_id', $qr->id)->count()}}

But I want to do it somehow like this in the foreach loop

 {{ $Qr->rating->count() }}

If this is somehow possible.

I get the relation, if I just output the first() of Qr and then var_dump($qrs->ratings->toArray())

But I don't know how to get the count Number of ratings in combination with the foreach loop. Any help would be dearly appreciated.

  • 写回答

2条回答 默认 最新

  • douliangbian7323 2014-04-25 17:05
    关注

    Couple of things wrong here:

    // view:
    @foreach($qrs as $qr->rating) 
    // should be: 
    @foreach($qrs as $qr)
    
    // controller:
    $unit = Unit::all()->first();
    $qrs = Qr::all()->first();
    // this way you get all Units then fetch first Unit from the collection,
    // the same with Qrs, so change it to:
    $unit = Unit::all(); // do you need it at all?
    $qrs = Qr::with('ratings')->get();
    

    This will solve the problem and in the foreach loop you will be able to access $qr->ratings->count() which will be Collection method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗