在 Laravel 5.1 中,使用 Eloquent ORM,如何为每个关系更新单个属性?
In Laravel 5.1, using Eloquent ORM, how does one update a single attribute for every relation?
我到处找资料,就是搞不懂这个。假设我已经建立了一个具有 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);
}
这成功地 return 收集了所有相关模型。但是,我无法弄清楚如何为 belongsTo 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]);
}
}
这行得通,但我只知道有一些 "Eloquent," 方法可以做到这一点......对吗?
根据 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]);
}
}
我到处找资料,就是搞不懂这个。假设我已经建立了一个具有 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);
}
这成功地 return 收集了所有相关模型。但是,我无法弄清楚如何为 belongsTo 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]);
}
}
这行得通,但我只知道有一些 "Eloquent," 方法可以做到这一点......对吗?
根据 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]);
}
}