查询建立在多个表上

时间:2018-11-13 07:19:35

标签: laravel eloquent

我想使用Eloquent运行以下查询。

SELECT * FROM `orders`, `order_status` WHERE `orders`.`id` = `order_status`.`order_id` AND `orders`.`payment` > 0 AND `order_status`.`status_id` = 1

但是我对如何在Eloquent上应用最后一个条件(order_status.status_id = 1)感到困惑,因为它在另一个表上。我应该加入他们,还是可以通过雄辩的关系来申请?

表的数据库架构:

订单:

Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps('');
            $table->integer('sender_id');
            $table->integer('sender_franchise');
            $table->integer('sender_agent')->nullable();
            $table->integer('recipient_franchise');
            $table->integer('recipient_agent')->nullable();
            $table->integer('category_id');
            $table->decimal('payment');
            $table->decimal('final_payment');
            $table->string('order_code');
            $table->decimal('extra_charge');
            $table->integer('recipient_id');
            $table->decimal('condition_charge')->nullable();
            $table->decimal('condition_amount')->nullable();
            $table->boolean('condition_charge_recipient')->nullable();
            $table->integer('quantity');
            $table->integer('created_by');
            $table->string('receiver_name')->nullable();
            $table->string('receiver_ph')->nullable();
            $table->text('shipping_address')->nullable();
});

ORDER_STATUS:

Schema::create('order_status', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('order_id');
            $table->integer('status_id');
            $table->integer('created_by');
            $table->timestamps('');
});

3 个答案:

答案 0 :(得分:1)

您应该尝试这个

Order::join('order_status', 'orders.id' = 'order_status.order_id')
    ->where('orders.payment', '>', 0)
    ->where('order_status.status_id', '=', '1');

答案 1 :(得分:0)

try this one see

DB::table('orders')->join('order_status',function($join){
              $join->on('order_status.order_id','=','orders.id')
                      ->where('order_status.status_id',1)    
})->where('orders.payment','>',0)->get()

答案 2 :(得分:0)

您可以通过两种方式实现这一目标。

要加入,请尝试以下方法:

Order::join('order_status', 'orders.id', '=', 'order_status.order_id')
->where('orders.payment', '>', 0)
->where('order_status.status_id', 1);

对于关系,请尝试以下方法:

Order::with('status')->where('orders.payment', '>', 0)->whereHas('status', function ($q) use ($statusId) {
    $q->where('status_id', $statusId);
});

如果$ statusId是固定的,则可以直接将其指定为1。

还要在您的订单模型中定义此关系。

public function status()
{
    return $this->belongsToMany(Status::class, 'order_status', 'order_id', 'status_id', 'id', 'id');
}