Thinkphp6 Error: constraint violation: 1052 Column ‘id’ in where clause is ambiguous

Cause

Show a column model

<?php
declare (strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Column extends Model
{

    public function articles()
    {

        return $this->belongsToMany(Article::class, 'column_article', 'article_id', 'column_id');
    }


    public function hasArt($article_id)
    {
        return $this->articles()->where('id', $article_id)->count();
    }

}

Wrong package when using

constraint violation: 1052 Column 'id' in where clause is ambiguous...

The reason for the error is that the relationship model of ThinkPHP does not know which table ID it is,

Here, we need to know which table it belongs to when sorting, so we also need to specify the table name when using it (Note: it needs to be prefixed)

    public function hasArt($article_id)
    {
        return $this->articles()->where('lu_article.id', $article_id)->count();
    }

Similar Posts: