Question

I have a table of categories in which my categories and their title and thumbnails are stored.

I have another table in which images are stored.

The third table is a joint table. I store in each record of it, the id of the image and the id of the category.

Table Schema:

id
cat_id
item_id

Now I want to get a cat_id by query_string and then pass it to the function for it to get the list of all images with this category in the database.

I'm confused about how to write the method. I have written the following method for CategoryList model which throws error:

class CategoryList extends Eloquent
{

    protected $table = "categories_list";

    function Images ()
    {
        return $this->hasMany("Image", 'id');
    }
} 

And here is the usage in the Image model:

return CategoryList::Images()->where("cat_id", '=', $catid)->get()->toArray();

But it throws the following error:

{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select * from `images` where `images`.`id` is null and `cat_id` = 19)","file":"C:\\wamp\\www\\aone\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php","line":539}}
Was it helpful?

Solution

class Category extends Eloquent {

    public function images()
    {
        return $this->belongsToMany('Image');
    }
}

Then do:

$images= Categorie::find($catid)->images;

In this case, your pivot table is 'category_image', but if you need to choose another name, it must be specified

return $this->belongsToMany('Image', 'your_pivot_table_name', 'cat_id', 'item_id');

Please visit http://laravel.com/docs/eloquent#many-to-many for more information

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top