Note that there are some explanatory texts on larger screens.

plurals
  1. POLaravel 4 Eloquent: multiple relationship methods referencing the same model?
    primarykey
    data
    text
    <p>I have DB tables as follows:</p> <pre><code>images: id name url etc places: id image_id name url etc image_place: image_id place_id </code></pre> <p>Places and images have a many-to-many relationship, but each place is also assigned a single image, which is used as the thumbnail in lists. So a place may "belong to" an image in a one-to-many relationship. Therefore I tried this in Laravel 4:</p> <p>models/Place.php:</p> <pre><code>public function image() { return $this-&gt;belongsTo('Image'); } public function images() { return $this-&gt;belongsToMany('Image'); } </code></pre> <p>But when I try to access $place->image, I get an error: "call to unknown method getResults()." </p> <p>I've done some experimenting and found these workarounds:</p> <ol> <li><p>If I remove the images() method, $place->image works as expected. I don't use images() currently, so this is my solution for now, but certainly I would like to have both available.</p></li> <li><p>If I replace the image() function with: return Image::where('id', $this->image_id)->first(); then I can access the object via $place->image(). But I can't do eager loading, which is important since I use the thumbnails in long lists of results. Plus I don't like having to use the method() syntax for just this one property.</p></li> </ol> <p>I also tried renaming the methods, e.g. image() and photos(), but it made no difference.</p> <p>Is accessing the same model with different types of relationships not possible in Laravel, or am I missing something?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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