【问题标题】:Leaving reviews on multiple products and Laravel relations对多个产品和 Laravel 关系发表评论
【发布时间】:2017-10-30 06:46:46
【问题描述】:

我有订购系统,当用户订购一些产品时,他可以留下产品反馈。

我的问题是同一订单中有多个产品。我想在每个产品上放置按钮leave feedback

在我的控制器中我有这个

public function orderView($orderId)
{       
    $order = Order::where('order_id', $orderId)->where('status', 1)->where('user_id', Auth::user()->user_id)->first();
    $reviews = Review::where('user_id', Auth::user()->user_id)->get();        

    return View::make('order_details', [
        'order' => $order,
        'reviews' => $reviews
    ]);
}

函数查询orders表和reviews表。然后在我尝试这样做的页面上

@foreach($reviews as $review)   
    @if($item->product_id == $review->product_id)                                   
        @if($review->rating_published == 0)
            <a class="btn btn-warning" href="">Wating for Approval</a>
        @else   
            <a class="btn btn-warning" href="">Edit Review</a>                                  
        @endif                                          
    @else
        <a class="btn btn-warning" href="">Leave Review</a>
    @endif
@endforeach

目前的问题是,如果没有来自登录用户的评论,我在页面上看不到“留下评论”按钮。

我的评论模型有

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'user_id');
}
public function item()
{
    return $this->belongsTo('App\Product', 'product_id','product_id');
}

产品型号

public function reviews()
{
    return $this->hasMany('App\Review', 'product_id'); 
}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    你可以使用@forelse刀片语法

    @forelse ($users as $user)
        <li>{{ $user->name }}</li>
    @empty
        <p>No users</p>
    @endforelse
    

    所以你的代码可以重写如下

    @forelse($reviews as $review)   
        @if($item->product_id == $review->product_id)                                   
            @if($review->rating_published == 0)
                <a class="btn btn-warning" href="">Wating for Approval</a>
            @else   
                <a class="btn btn-warning" href="">Edit Review</a>                                  
            @endif                                          
        @endif
    @empty
            <a class="btn btn-warning" href="">Leave Review</a>
    @endforelse
    

    因此,如果评论数组为空,它将显示留下评论消息

    【讨论】:

    • 您好,谢谢您的回答。当用户订单包含 2 个或更多产品并且一个产品有反馈时,存在一个问题。同订单的其他产品因条件原因不再有按钮Leave Review
    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    相关资源
    最近更新 更多