【问题标题】:eloquent morphmany relationship - update and/or save雄辩的 morphmany 关系 - 更新和/或保存
【发布时间】: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


    【解决方案1】:

    这很简单:

    // get only applicable fields
    $input = Input::only('address','city','state','zip');
    
    // get existing or instantiate new address
    $address = Address::firstOrNew($input);
    
    // associate the address with the user
    // btw I would rather call this relation addresses if it's morhpmany
    User::find($userId)->addresses()->save($address);
    

    不确定你从哪里得到泰勒的答案,但我认为这不应该适用于这种情况。无论如何它都无法工作。

    【讨论】:

    • 首先,谢谢您的回答。我有一个问题,在 firstOrNew 中,它将如何确定我们是否没有传递地址的 id(特别是对于现有的)?在这种情况下,地址的 id 在 post 字段中。有什么想法吗?谢谢
    • 这是省略id 的方式。 Eloquent 会通过address,city,state,zip 组合找到现有的Address(地址或多或少是一个值对象,id 到最后根本不重要)或实例化新模型并将上述组合填充为其属性。先试试这个。
    • 再次感谢。如果用户编辑地址会发生什么?似乎它会插入一个新行,这肯定不是一个理想的结果。想法?
    • 好吧,就像我说的,地址几乎是价值对象,所以我认为不应该改变它。无论如何,如果你想编辑,只需传递id 并更新获取的行。当您创建新的时,只需创建 - 单一职责。
    • 知道了,非常感谢您的建议。对此,我真的非常感激。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多