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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line