Laravel 5.5:使用联接和where子句查询构建

时间:2019-03-20 16:25:11

标签: php mysql laravel laravel-5

我有两个桌子

'Orders' with Columns 

['subtotal', 'taxes', 'delivery_fee', 'total', 'discount', 'status', 'delivery_status','payment_status', 'special_instructions', 'address_id', 'store_id', 'user_id', 'delivery_profile_id','payment_method_id', 'type', 'scheduled_on'];

'Stores' with Columns

['name', 'tagline', 'image_url', 'delivery_time', 'minimum_order','delivery_fee', 'details', 'delivery_limit', 'area', 'address', 'longitude', 'latitude', 'preorder','serves_non_veg', 'cost_for_two', 'status', 'owner_id', 'apibot', 'admin_id','admin_mobile', 'opens_at', 'closes_at'];

我正在运行Laravel 5.5框架,并且很难构建查询。下面是我的完整代码,可从我的移动API根据请求的状态返回订单清单

        $orders = Order::where('store_id', Auth::user()->store->id);

        if($request->status) {
            $orders = $orders->where('status', $request->status);
        }

        // filter for active orders
        if($request->active_orders) {
            $orders = $orders->whereIn('status', ['new', 'accepted', 'preparing', 'dispatched']);
        }

        // for delivery tab in store app
        if($request->deliveries) {
            $orders = $orders->whereIn('status', ['accepted', 'preparing', 'dispatched'])
                ->where('delivery_profile_id', '<>', null)
                ->whereIn('delivery_status', ['allotted', 'started', 'complete']);
        }

在下面的代码中,我需要添加“联接和where子句”组合以通过订单联接商店

$orders = Order::where('store_id', Auth::user()->store->id);

例如:常规SQL查询如下

   Select * From Orders, Stores Where Stores.id=Orders.store_id and Stores.admin_id = 17

我尝试了可能的解决方案,但未成功。谢谢你。

3 个答案:

答案 0 :(得分:1)

您首先需要在belongsTo模型上创建一个Store来建立关系:

public function store() {
   return $this->belongsTo(\App\Store::class);
}

然后您的查询将如下所示:

$orders = Order::with(['store' => function($query) {
    return $query->where('admin_id', auth()->user->id)
}]);

答案 1 :(得分:0)

看看它是否对您有用:

$result = DB::table('Orders as o')
->join('Stores as s', 's.id', '=', 'o.store_id')
->where('s.admin_id', auth()->user->id)
->get();

答案 2 :(得分:0)

此代码有效

$orders = Order::with(['store' => function($query) {
return $query->where('admin_id', auth()->user->id)}]);

有关相同的Join和WHere子句的新查询

$ this-> pushNotifications [] = new PushNotification($ this-> order-> store-> user-> fcm_registration_id,'New Order','New Order');

如何调用基于admin_id的User-> fcmRegistration? 我尝试过 $ this-> order-> store->'admin_id'-> user-> fcm_registration_id没有运气。

请帮助。