我正在尝试更新Laravel中一对多关系的关系。不幸的是我找不到任何文件。任何人都可以帮助我吗?
这是我到目前为止所做的:
class Account extends Eloquent
{
public function users()
{
return $this->hasMany('User');
}
}
class User extends Eloquent
{
public function account()
{
return $this->belongsTo('Account');
}
}
现在我正在尝试更新USER(1)>的关系。帐户(50)到USER(1)>帐户(99)。我该怎么做?我尝试了以下方法:
$account = Account::find(99);
User::find(1)->account()->save($account);
但是这不起作用:-(任何帮助都非常感谢!!
更新:
以下作品:
$user = User::find(1);
$user->account_id = 99;
$user->save();
......但是必须有一个比上面更好的解决方案,对吧?
它与save()和attach()方法在多对多关系中工作,以更新表之间的关系(来自关系的两侧)。在一对多关系中,似乎不支持attach()方法。
答案 0 :(得分:34)
$account = Account::find(99);
User::find(1)->account()->associate($account)->save();
我在官方文档中找不到associate()方法。因此,如果其他人正在寻找解决方案。你走了!
答案 1 :(得分:6)
嘿,你可以参考laravel docs来解决问题。
链接http://laravel.com/docs/4.2/eloquent#inserting-related-models
$account = Account::find(10);
$user->account()->associate($account);
$user->save();
答案 2 :(得分:4)
我就是这样做的
//step 1
我的迁移
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
class CreateUserDetailsTable extends Migration {
public function up()
{
Schema::create('user_details', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned()->unique('user_id', 'user_details_user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->enum('gender', array('male', 'female'))->nullable();
$table->string('city')->nullable();
$table->date('date_of_birth')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::drop('user_details');
}
}
然后
//step 2
我的基础模型
class UserDetail extends Eloquent {
protected $guarded = array();
protected $table = 'user_details';
public function user()
{
return $this->belongsTo('User');
}
}
class User extends Eloquent {
protected $table = 'users';
protected $guarded = array();
public function detail()
{
return $this->hasOne('UserDetail');
}
}
然后
//step 3
我的控制器 - 更新user_details架构
//When Updating records i get the raw data from say an input
$detail = Input::all();
//then find the user
$user = User::find(1);
//then update the details
$detail = $user->detail()->update($detail);
//then respond back with the detail
Response::json($detail);
我的控制器 - 创建user_details架构
//again get data input from source, the source does not come with user id
$detail = Input::all();
//when creating new record
$detail = new UserDetail($detail);
$detail = $user->detail()->save($detail);
return Response::json($detail);
这就是使用Laravel 4的belongsTo关系来创建和更新新记录
答案 3 :(得分:0)
**
尝试
$user = User::find();
$account = Account::find()->user()->save($user)
道歉,我不明白想要完成什么。