Home > Mobile >  laravel-8 whreRelation says Column not found: 1054 Unknown column 'relation' in 'wher
laravel-8 whreRelation says Column not found: 1054 Unknown column 'relation' in 'wher

Time:11-22

Laravel version:8.36.2

Article

  • id

RelationalArticle

  • article_id
  • product_id

Product

  • id

article hasMany relational_article.

product belongsTo relational_article

When I make

Product::whereRelation('relational_article', 'relational_article_id', '=', $article_id)->get();

I mean I want to retrieve products from article_id.

Then I got

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'relation' in 'where clause' (SQL: select * from `products` where `relation` = relational_articles and `products`.`deleted_at` is null)

What should I check for it?

CodePudding user response:

Article and Product should have a 'belongsToMany' relationship;

Your intermediate table

public function up()
    {
        Schema::create('article_product', function (Blueprint $table) {
            $table->id();
            $table->foreignId('article_id')->constrained();
            $table->foreignId('product_id')->constrained();
            $table->timestamps();
        });
    }

Article.php

public function products()
    {
        return $this->belongsToMany(Product::class);
    }

Product.php

public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

All products that belong to article with id of 1

$article = App\Models\Article::find(1)
$article->products

CodePudding user response:

You created pivot table for Article and Product model but you used belongsTo and hasMany in your relationships. This is wrong because because you are looking into oneTomany instead of manyToMany relationship. So do this instead

in Article.php model

public function products()
    {
        return $this->belongsToMany(Product::class);
    }

in Product.php model

public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

in your controller do this if you want to get all articles and products

public function getArticleById($article_id){    
  $article = App/Model/Article::with('products')->where('id',$article_id)-get()
  return $article
}
  • Related