【问题标题】:Eloquent - Make a where request on a request with jointEloquent - 根据联合请求发出 where 请求
【发布时间】:2014-11-14 08:57:09
【问题描述】:

我想用 Eloquent(在 Laravel 中)提出这个请求:

$user = User::find(1);
$product = $user->products()->where('id', 1)->first();

但是列 ID 在表用户和表产品中,所以我遇到了一个错误(列不明确)。我想在代码中不设置“产品”的情况下使用它(因为表名最终可能会改变......)。

如何解决这个问题?

【问题讨论】:

  • 你试过 product.id 代替 id 吗?
  • 我已经编辑了我的问题:它会起作用,但我不想硬编码表名,因为它们最终会改变......
  • 如果不明确你想要从哪里得到什么,你就不能真正做到,这就像你想从自己身上拿一块,但你不知道从哪里伸手
  • 只是这样的想法,但这里似乎很清楚,我想检索用户 ID 为 1 的第一个产品。如果我想要 ID 为 1 的用户的第一个产品,我想我会这样写:$user->where('id', 1)->products()->first();.
  • 请注意 - 这与 users 表无关。您必须通过枢轴链接这些模型,对吗?顺便说一句,不确定你为什么重复你的问题?

标签: php laravel eloquent


【解决方案1】:

在这种情况下,您可以使用如下内容:

$id = 1;
$user = User::with(array('products' => function($q) use($id){

    // You may use this
    $table = $q->getRelated()->getTable();
    $q->where("{$table}.id", $id);

    // Or if this is a primary Key then you mau use this
    $q->where($q->getRelated()->getQualifiedKeyName(), $id);

}))->find($id);

// Get the first product
$product = $user->products->first();

【讨论】:

    【解决方案2】:

    您必须动态获取表名。详情请见this question

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      相关资源
      最近更新 更多