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]);
    
            }
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题