thinkphp6模型多对多报错constraint violation: 1052 Column 'id' in where clause is ambiguous

时间:2021-10-10
本文章向大家介绍thinkphp6模型多对多报错constraint violation: 1052 Column 'id' in where clause is ambiguous,主要包括thinkphp6模型多对多报错constraint violation: 1052 Column 'id' in where clause is ambiguous使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

产生原因

展示一个专栏模型

<?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();
    }

}

使用的时候会包错

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

报错的原因是thinkphp的RelationModel不知道是哪个表的id,
这里我们在排序时候就要写明白是哪个表的,所以使用的时候还需要指定表名(注意:需要加前缀)

    //判断专栏是否拥有该文章
    public function hasArt($article_id)
    {
        return $this->articles()->where('lu_article.id', $article_id)->count();
    }

原文地址:https://www.cnblogs.com/lujiahao/p/15390278.html