如何在Laravel 4中更新现有的雄辩关系? [英] How can I update an existing Eloquent relationship in Laravel 4?
问题描述
我正在尝试更新Laravel中一对多关系的关系.不幸的是我找不到任何文档.谁能帮我吗?
I am trying to update the relationship of a one-to-many relationship in Laravel. Unfortunately I couldn't find any documentation for it. Can anyone help me?
这是我到目前为止所拥有的:
This is what I have so far:
class Account extends Eloquent
{
public function users()
{
return $this->hasMany('User');
}
}
class User extends Eloquent
{
public function account()
{
return $this->belongsTo('Account');
}
}
现在,我尝试将USER(1)> ACCOUNT(50)的关系更新为USER(1)> ACCOUNT(99).我该怎么做?我尝试了以下方法:
Now I am trying to update the relationship from USER(1) > ACCOUNT(50) to USER(1) > ACCOUNT(99). How would I do this? I tried the following:
$account = Account::find(99);
User::find(1)->account()->save($account);
但这不起作用:-(任何帮助深表感谢!
But that doesn't work :-( Any help deeply appreciated!!
更新:
以下作品:
$user = User::find(1);
$user->account_id = 99;
$user->save();
...但是必须有一种更好的解决方案,对吗?
...but there MUST be a better solution like the one above, right?
它与save()和attach()方法在多对多关系中工作,以更新表之间的关系(从关系的两侧).在一对多关系中,似乎不支持attach()方法.
It works in many-to-many relationships with both the save() and attach() method to update the relationship between tables (from both sides of the relationship). In one-to-many relationships the attach() method doesn't seem to be supported.
推荐答案
泰勒·奥特威尔(Taylor Otwell)的官方答案如下:
Taylor Otwell's official answer is the following:
$account = Account::find(99);
User::find(1)->account()->associate($account)->save();
我在官方文档中找不到associate()方法.因此,如果有人正在寻找解决方案.来啦!
I couldn't find the associate() method in the official docs. So if someone else is looking for a solution to this. Here you go!
这篇关于如何在Laravel 4中更新现有的雄辩关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!