2
DB::select("SELECT products.* ,categories.* FROM products 
INNER JOIN category_products ON category_products.product_id = products.id
INNER JOIN categories ON category_products.category_id = categories.id 
WHERE categories.slug='$slug'")

This row query working fine but I can not access their relation like

$product->Categories->first()->name

@foreach($product->Images as $image)

My product Model below :

class Product extends Model
{
    public function Category(){
        return $this->hasMany(CategoryProduct::class);
    }
    public function getCategory($id){
       return Category::find($id)->name;
    }
    public function Images(){
       return $this->hasMany(Image::class);
    }

    public function Categories()
    {
        return $this->belongsToMany(Category::class, 'category_products');
    }
}

so how can convert my code to Laravel eloquent

2

1 Answer 1

3

Please check this documentation https://laravel.com/docs/5.0/eloquent#querying-relations

According to documentation, you can change your code like this:

$products= Product::whereHas('Categories', function($q) use ($slug)
{
    $q->where('slug', $slug);

})->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.