【问题标题】:In Laravel 5.1, using Eloquent ORM, how does one update a single attribute for every relation?在 Laravel 5.1 中,使用 Eloquent ORM,如何为每个关系更新单个属性?
【发布时间】:2015-07-15 19:45:24
【问题描述】:

我一直在到处搜索文档,但我无法弄清楚这一点。假设我已经建立了一个具有 hasMany 关系的模型,反之如下:

    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');
    }

}

并且我已确保某些子帐户的值与 master_account_id 列中主帐户的主 ID 匹配。

我已经在我的控制器中通过 dd()ing 值测试了这种关系,如下所示:

public function edit(MasterAccount $masterAcct)
    {

        dd($masterAccount->subAccounts);

    }

这确实成功地返回了所有相关模型的集合。但是,我无法弄清楚如何为属于 MasterAccount 的每个模型更新单个属性——不应该有这样的级联方法吗?我通过这样做破解了它:

<?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]);

        }
}

这行得通,但我只知道有一些“雄辩”的方法可以做到这一点.....对吗?

【问题讨论】:

    标签: php laravel eloquent laravel-5.1


    【解决方案1】:

    根据documentation,这应该可以工作:

    <?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]);
    
            }
    }
    

    【讨论】:

    • 不再需要$id 变量。
    • 是的!谢谢你。你赢了!我在 API 文档中看到了这一点,但这里没有提到它:laravel.com/docs/5.1/eloquent-relationships...thanks 再次
    • 只用源码或者api文档,虽然比较费时间,但是比较有用
    猜你喜欢
    • 2016-02-11
    • 2023-03-28
    • 2020-03-25
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多