drbe16008 2015-07-15 19:45
浏览 65
已采纳

在Laravel 5.1中,使用Eloquent ORM,如何为每个关系更新单个属性?

I've been searching the documents everywhere and I can't figure this one out. Suppose I have set up a model with a hasMany relationship and the inverse like this:

    class MasterAccount extends Model {

    //master_account_id exists as a foreign key in sub_account table 
    //and references primary key in master_account table as
    //defined in the migrations I set up for this
    public function SubAccounts()
    {
        return $this->hasMany('App\SubAccount');
    }

}

And I've made sure that some sub accounts have values matching the master account's primary id in the master_account_id column.

I've tested the relationship by dd()ing values in my controller like this:

public function edit(MasterAccount $masterAcct)
    {

        dd($masterAccount->subAccounts);

    }

And this does successfully return a collection of all the related models. However, I cannot figure out how I would update a single attribute for every model that belongsTo MasterAccount -- shouldn't there be a way to cascade like this? I hacked it to work by doing this:

<?php namespace App\Http\Controllers;

use App\SubAccount;

public function update(MasterAccountRequest $request, MasterAccount $masterAccount)
    {
        //current request id
        $id = $masterAccount->id;

        //cascade global value to related Accounts
        if ($request->some_value == 1)
        {
            //look more into this... ARGH!!!
            SubAccount::where('master_account_id', '=', $id)->update(['this_value' => 1]);

        }
}

And this works but I just KNOW there is some "Eloquent," way to do this.....right?

  • 写回答

1条回答 默认 最新

  • doulian1852 2015-07-15 19:49
    关注

    According to the documentation this should work:

    <?php namespace App\Http\Controllers;
    
    use App\SubAccount;
    
    public function update(MasterAccountRequest $request, MasterAccount $masterAccount)
        {
            //current request id
            $id = $masterAccount->id;
    
            //cascade global value to related Accounts
            if ($request->some_value == 1)
            {
                //look more into this... Wooooot!!!
                $masterAccount->SubAccounts()->update(['this_value' => 1]);
    
            }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置