0

I would like to make this request with Eloquent (in Laravel) :

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

But the column ID is in the table user AND in the table product, so I've got an error (column ambiguous). I want to use it without set "products" in hard in the code (because the table name could eventually change...).

How to resolve this ?

Kevin
  • 1,000
  • 2
  • 10
  • 31
  • Have you tried product.id instead of id? – andy Sep 19 '14 at 17:36
  • I've edited my question : it will work, but I don't want to hard code the table name as they can eventually change... – Kevin Sep 19 '14 at 17:43
  • You cant really do it without defining what you want from where, this is like you want to take a piece from the self but you dont know where to reach out –  Sep 19 '14 at 17:47
  • Just an idea like that, but it seems clear here that I want to retrieve the first product with the ID 1 of the user. If I would like the first product of the user with the ID 1, I suppose I would have written this : `$user->where('id', 1)->products()->first();`. – Kevin Sep 19 '14 at 17:54
  • Just a note - this has nothing to do with the `users` table. You must link these models through pivot, right? Btw not sure why you duplicate your questions? – Jarek Tkaczyk Sep 19 '14 at 18:02
  • I've duplicate it at the beginning because it doesn't seems the same question in my head at the beginning. And no, I don't need a pivot : a product belongs only to one user. – Kevin Sep 19 '14 at 18:09

2 Answers2

1

In this case you may use something like this:

$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();
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

You will have to get the table name dynamically. See this question for further details.

Community
  • 1
  • 1
andy
  • 2,002
  • 1
  • 12
  • 21