【发布时间】:2014-11-23 14:05:29
【问题描述】:
我在这里看到了类似的 Q,但没有找到任何合适的答案,因此再次询问。如果你知道任何线程,请指导我,
我有
模型用户和模型属性都具有地址
class Address {
protected $fillable = ['address','city','state','zip'];
public function addressable(){
return $this->morphTo();
}
}//Address
class User extends Eloquent {
protected $fillable = ['first_name','last_name', 'title'];
public function address(){
return $this->morphMany('Address', 'addressable');
}
}//User
class Property extends Eloquent {
protected $fillable = ['name','code'];
public function address(){
return $this->morphMany('Address', 'addressable');
}
}//Property
有什么方法可以更新地址的 UpdateIfNotCreate 类型方法以及与用户/属性相关联吗?
Taylor Otwell 的官方回答,
$account = Account::find(99);
User::find(1)->account()->associate($account)->save();
因为我遇到异常而无法正常工作
消息:“调用未定义的方法 Illuminate\Database\Query\Builder::associate()”
类型:“BadMethodCallException”
我解决问题的方法如下:
$data = Input::all();
if($data['id'] > 0){
$address_id = $data['id']; unset($data['id']);
$address = Address::find($address_id)->update($data);
}//existing
else{
$address = new Address($data);
User::find($user_id)->address()->save($address);
}//add new
我可以使用不同的路由( PUT 到 /update{id} 和 POST 到 / ) 但在我的情况下,新的和现有的记录都在同一条路线( /update )
你们能推荐更好的方法吗?
谢谢,
【问题讨论】:
标签: laravel-4 eloquent polymorphic-associations