繁体   English   中英

在哪里有Laravel更新关系列

[英]Laravel Updating Relationship Column in WhereHas

我想用wherehas更新模型中的列。 但是,我不确定如何执行此操作。 这是我的查询下面

$unused = Sale::whereHas('salesdetails',function($query) {
             $query->where('product_id', '<=', 24)->where('switch', 1);
        })->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now)->update(['switch' => 0]);

销售模式

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sale extends Model
{
    protected $table = 'sales';

    protected $primaryKey = 'id';
    public $timestamps = false;

    public function user()
    {
        return $this->belongsTo('App\User', 'member_id', 'id');
    }

    public function guest()
    {
        return $this->belongsTo('App\Guest', 'guest_id', 'id');
    }

    public function salesdetails()
    {
        return $this->hasOne('App\Sales_details','sales_id', 'id');  
    }

    public function discount()
    {
        return $this->hasOne('App\Discount','id', 'discount_id');  
    }
}

销售细节模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sales_details extends Model
{
    protected $table = 'sales_details';

    protected $primaryKey = 'id';
    public $timestamps = false;

    public function sale()
    {
        return $this->belongsTo('App\Sale', 'sales_id', 'id');
    }

    public function product()
    {
        return $this->belongsTo('App\Product', 'product_id');
    }


}

在上面的查询中,我想将所有开关从salesdetails关系更新为“ 0”。 我该怎么办?

您尝试的是错误的,您应该这样尝试

Sale::where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now)->salesdetails()->where('product_id', '<=', 24)->where('switch', 1)->update(['switch' => 0]);

我假设transaction_date列在Sale模型中。

由于您是在更新SalesDetails而不是Sale,因此我会反转查询,以便更新实际上在SalesDetails而不是Sale上:

Sales_details::whereHas('sale', function($query) use ($now){
    $query->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now)
})->where('product_id', '<=', 24)->where('switch', 1)->update(['switch' => 0]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM