سؤال

I am trying to show 1 record out of highlights, with both Services and Pages joined into this table to show their details (instead of only showing service_id and page_id)

In my HighlightsController I have the following to get the items from my database:

 $highlight = Highlight::where('id', $id)->with(array('Service','Page'))->get();

I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'services.highlight_id' in 'where         clause' (SQL: select * from `services` where `services`.`highlight_id` in (1))

I know that this column doesn't exist because it's looking in the wrong table. I don't know what I'm doing wrong. I've been over and over my models compairing it with my SQL and thinking where I went wrong

Here are all the details that could be useful:

The SQL I want to get:

SELECT * FROM highlights 
LEFT JOIN pages ON pages.id = highlights.page_id
LEFT JOIN services ON services.id = highlights.service_id
WHERE highlights.id = '1'

My tables:

Highlights

+------------+
| Field      |
+------------+
| id         |
| service_id |
| page_id    |
| text       |
+------------+

services

+------------+
| Field      |
+------------+
| id         |
| title      |
| description|
+------------+

pages

+------------+
| Field      |
+------------+
| id         |
| name       |
+------------+

Models and their functions:

class Highlight extends Eloquent
{
    function Service(){
        return $this->HasMany('Service');
    }

    function Page(){
        return $this->HasMany('Page');
    }
}

class Service extends Eloquent
{
    function Highlight(){
        return $this->HasMany('Highlight');
    }
}

class Service extends Eloquent
{
    function Highlight(){
        return $this->belongsTo('Highlight');
    }
}
هل كانت مفيدة؟

المحلول

To make it clear - eager loading (with() method) does not join anything, but runs another query per each loaded relation with WHERE id IN clause.

Change those relations as they are completely incorrect:

// Let's call methods snakeCased just for clarity and sticking to the convention
// and singular or plural depending on what is returned

class Highlight extends Eloquent
{
    function service(){
        return $this->belongsTo('Service'); // returns single Model
    }

    function page(){
        return $this->belongsTo('Page'); // same as above
    }
}

class Service extends Eloquent
{
    function highlights(){
        return $this->HasMany('Highlight'); // returns Collection of Models
        // you can have hasOne instead, depending on your app
    }
}

class Service extends Eloquent
{
    function highlights(){
        return $this->hasMany('Highlight'); // again Collection
    }
}

Then you call it:

// returns Collection, so let's call it plural:
$highlights = Highlight::where('id', $id)->with(array('service','page'))->get();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top