【问题标题】:Update many records in a laravel relationship更新 laravel 关系中的许多记录
【发布时间】:2014-06-18 17:25:34
【问题描述】:

我尝试在 Laravel 中使用 4 个表,但我不知道如何使用 eloquent 执行特定查询。我想更新属于某个用户(通过 product_id)且payout_id 为空的所有订单。

此原始 sql 语句有效,但我不确定如何为此使用 eloquent..也许是 sync

UPDATE order_items i JOIN products p on (i.product_id = p.id)  SET i.payout_id = null where p.user_id = 3

用户模型

产品型号 FK: user_id

订单模式 FK:product_id FK:payout_id

支付模式

非常感谢任何帮助!

【问题讨论】:

    标签: laravel eloquent foreign-key-relationship


    【解决方案1】:

    您需要为表ip 创建模型,有关模型创建的完整信息,请参阅http://laravel.com/docs/eloquent

    i 的模型中,您将创建与p 的关系:

     public function p()
     {
         return $this->('p','id','product_id');
     }
    

    然后您可以按如下方式运行查询:

    $results = i::with('p')
    ->where('user_id', '=', 3)
    ->update(array('payout_id' => null));
    

    【讨论】:

    • 感谢您的建议!不幸的是,这给了我 Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: update order_items set payout_id = 8, updated_at = 2014-05-02 15:52:21 where @987654331 @ = 3 和 payout_id 为空)
    • 抱歉弄混了,有点错别字,怎么样。
    【解决方案2】:
    First define a function orders in User Model
        public function orders()
        {
            return $this->hasManyThrough('Orders', 'Product','user_id','product_id');
        }     
    
    
    
        User::where('id','=',$userid)->with(array('orders'=>function($query){
            $query->where('payout_id','=',0)->update(array('payout_id'=>$updatevalue));
        }))->first();
    

    【讨论】:

    • 谢谢!这似乎应该有效,但我可能会遗漏一些东西。 $payout_id = $payout->id; User::where('id','=',$user_id)->with(array('orderItems'=>function($query){ $query->where('payout_id',NULL)->update(array('payout_id'=>$payout_id)); }))->first(); 给我未定义的变量 $payout_id?范围问题?如果我用静态值 (11) 替换变量,我会得到`完整性约束违规:字段列表中的 1052 列 'updated_at' 不明确
    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 2016-07-29
    • 2017-04-27
    • 2021-08-21
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多