【问题标题】:laravel-8 whreRelation says Column not found: 1054 Unknown column 'relation' in 'where clause'laravel-8 whreRelation 说 Column not found: 1054 Unknown column 'relation' in 'where Clause'
【发布时间】:2021-12-31 19:56:02
【问题描述】:

Laravel 版本:8.36.2

文章

  • 身份证

关系文章

  • article_id
  • product_id

产品

  • 身份证

文章有很多相关的文章。

产品属于relational_article

当我制作时

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

我的意思是我想从 article_id 检索产品。

然后我得到了

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)

我应该检查什么?

【问题讨论】:

  • whereRelation() 会将WHERE relation = 添加到您的查询中,您正在寻找whereHas() laravel.com/docs/8.x/…
  • relational_article 是您模型中的关系名称?

标签: laravel eloquent laravel-8


【解决方案1】:

Article 和 Product 应该具有“belongsToMany”关系;

你的中间表

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

文章.php

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

产品.php

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

属于 id 为 1 的文章的所有产品

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

【讨论】:

    【解决方案2】:

    您为 Article 和 Product 模型创建了数据透视表,但您在关系中使用了 belongsTo 和 hasMany。这是错误的,因为您正在研究 oneTomany 而不是 manyToMany 关系。所以改为这样做

    在 Article.php 模型中

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

    在 Product.php 模型中

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

    在您的控制器中 如果您想获取所有文章和产品,请执行此操作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2020-10-13
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多