Php 雄辩-根据联合请求提出where请求

Php 雄辩-根据联合请求提出where请求,php,laravel,eloquent,Php,Laravel,Eloquent,我想以雄辩的口吻提出这一请求(用拉拉维尔语): 但是列ID在表用户和表产品中,所以我有一个错误(列不明确)。我希望在代码中不使用硬设置“products”(因为表名最终可能会更改…) 如何解决此问题?您必须动态获取表名。有关更多详细信息,请参阅。在这种情况下,您可以使用以下内容: $id = 1; $user = User::with(array('products' => function($q) use($id){ // You may use this $table

我想以雄辩的口吻提出这一请求(用拉拉维尔语):

但是列ID在表用户和表产品中,所以我有一个错误(列不明确)。我希望在代码中不使用硬设置“products”(因为表名最终可能会更改…)


如何解决此问题?

您必须动态获取表名。有关更多详细信息,请参阅。

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

$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();

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