我一直在到处搜索文档,但我无法弄清楚这一点。假设我已经建立了一个具有 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]);
}
}
这行得通,但我只知道有一些“雄辩”的方式来做到这一点......对吧?