【问题标题】:How do I perform a join in Laravel 5 with a `where` clause?如何使用“where”子句在 Laravel 5 中执行连接?
【发布时间】:2015-07-21 06:12:41
【问题描述】:

我有一张桌子,offers,用于购买的物品有 id。该项目存储在另一个表中,items。为了响应GET 请求,我想返回包含购买的完整项目对象。我该怎么做?

public function getBuys(Request $request)
{
    $usr_id = $request->input('usrid');

    $buys = Offer::where('buyer_id', '=', $usr_id)->get();
    return response()->json($buys);
}

【问题讨论】:

    标签: php mysql laravel laravel-5 query-builder


    【解决方案1】:

    现在您得到的用户提供的所有报价(购买)是否正确?如果您想获得包含所有优惠的特定商品(假设您在商品模型中设置了 realtionship):

    $item = Item::->with('offers')->find($itemId);
    

    编辑 如果您的 Offer 模型中有这种关系:

    public function item()
    {
        return $this->hasOne('App\Item');
    }
    

    你可以这样做:

    $buys = Offer::with('item')->where('buyer_id', '=', $usr_id)->get();
    

    【讨论】:

    • 我想退回所有 buys(优惠)及其各自的项目,而不仅仅是我今天收到的 item_id。
    • 我收到此错误:FatalErrorException in /var/www/html/laravel5/vendor/compiled.php line 9578: Class 'Game' not found
    • 我的Game.php 文件夹中有一个Game.php 模型。它是这样定义的:Offer.php 模型定义为: hasOne('Game');这就是我在控制器中所做的: $buys = Offer::with('game')->where('buyer_id', '=', $usr_id)->get();
    • 对不起,我应该指定的,我确实转储了自动加载。还是一样的错误。
    • 其实已经改成FatalErrorException in Model.php line 750: Class 'App/Game' not found
    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多