Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Alright, I <em>think</em> I understand your setup. Given the relations you stated, I think you'd define your models as follows:</p> <pre><code>&lt;?php class Product extends Eloquent { public function terms() { return $this-&gt;belongsToMany('Term')-&gt;withTimestamps(); } } &lt;?php class Taxonomy extends Eloquent { public function terms() { return $this-&gt;hasMany('Term'); } } &lt;?php class Term extends Eloquent { public function taxonomy() { return $this-&gt;belongsTo('Taxonomy'); } public function products() { return $this-&gt;belongsToMany('Product')-&gt;withTimestamps(); } } </code></pre> <p>Since your pivot is named and id'd correctly you shouldn't have to specify that info in the belongsToMany relationship, but if you want the timestamps to work you need the withTimestamps.</p> <p><strong>EDIT:</strong></p> <p>If you can look taxonomies up by id instead of slug, this will work:</p> <pre><code>$products = Product::all(); foreach($products as $product) { $term = $product-&gt;terms()-&gt;with('taxonomy')-&gt;where('taxonomy_id', '=', 2)-&gt;first(); echo $term-&gt;name; } </code></pre> <p>In the scenario above you could just store the taxonomy slug in the term table since it should be a unique key. Otherwise you could look over the terms and look for the one with the taxonomy that you want:</p> <pre><code>$products = Product::all(); foreach($products as $product) { $terms = $product-&gt;terms()-&gt;with('taxonomy')-&gt;get(); foreach($terms as $term) { if($term-&gt;taxonomy-&gt;slug == 'brand') { echo $term-&gt;name."&lt;br /&gt;"; } } } </code></pre> <p><strong>END EDIT</strong></p> <p>I have to admit that I'm a little lost though because your last two tables seem exactly the same and I'm wondering why you associate terms with products instead of taxonomies with products. I'm suspect that my solution won't work with the way you're relating things but if you related taxonomies with products instead it would work jut fine. </p> <pre><code>&lt;?php $product-&gt;taxonomy()-&gt;where('slug', '=', 'brand')-&gt;term; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload