【问题标题】:Attaching Order to User model using Eloquent使用 Eloquent 将订单附加到用户模型
【发布时间】:2017-03-31 07:49:14
【问题描述】:

所以我有两个模型,一个用户和一个订单(一个用户有很多订单)

在我的模型中关系设置如下:

用户模型

public function orders()
{
    return $this->hasMany('App\Order');
}

订单模式

public function user()
{
    return $this->belongsTo('App\User');
}

我正在使用以下代码将当前登录的用户附加到订单。

Auth::user()->orders()->attach($order_id);

我认为这是正确的,但在执行代码时出现此错误:

调用未定义的方法 Illuminate\Database\Query\Builder::attach()

谁能解释我做错了什么?

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • 我正在使用 Laravel v5.1 LTS

标签: php laravel eloquent


【解决方案1】:

attach 方法适用于many-to-many relationships。要将订单与场景中的用户关联,您应该能够以这种方式保存订单模型:

$order = App\Order::findOrFail($order_id);
Auth::user()->orders()->save($order);

【讨论】:

  • 您需要先使用$order = App\Order::findOrFail($order_id);获取$order
  • 正确。 $order 需要是订单模型的一个实例。我不确定您是否已经有了 - 感谢您指出这一点(我会将其添加到我的答案中以供参考)。
【解决方案2】:

我认为您必须使用 associate() 方法而不是 attach(),因为您正在更新 belongsTo 关系。

试试这个:

$order = App\Order::findOrFail($order_id);

$user->orders()->associate($order);

$user->save();

【讨论】:

  • 这只是返回未定义的方法 associate()
猜你喜欢
  • 2014-11-25
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2020-04-24
  • 2020-11-10
相关资源
最近更新 更多