0

Listing 和 Sub_Category 具有一对多的关系。列表属于一个 sub_category 并且 sub_category 有许多列表。

我的列表表“sub_catgory_id”上有一个列,并且我还在我的关系中指定了外键

Listing.php Model
public function sub_category()
{
    return $this->belongsTo('App\Sub_Category', 'sub_category_id', 'id');
}

尝试获取与子类别关联的所有列表

return $sub_category = \App\Sub_Category::with('listing')->get()

我收到此错误 => 未找到列:1054 'where 子句'中的未知列'listings.sub__category_id'。

我知道 eloquent 正在检查 sub__category_id(双下划线),但我已经深入这个项目,并希望将其保留为 sub_category_id(单下划线)。关于如何实现这一点的任何想法?

4

4 回答 4

1

我终于想出了一个解决办法。你可以驼峰你的模型。所以在我的例子中,我将我的模型从 Sub_Category 重命名为 subCategory,所以 eloquent 检查 sub_category_id。

于 2019-03-31T19:58:29.210 回答
0

我认为您应该设置如下:

1.Listening.php

public function sub_category()
{
    return $this->belongsTo('App\Sub_Category', 'id', 'sub_category_id');
}

2.Sub_Category.php:

public function listing()
{
    return $this->belongsTo('App\Listening', 'sub_category_id','id');
}

通过设置关系中的laravel 文档,我们首先设置foreign_key然后local_key像这样(示例来自 laravel 网站):

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
于 2019-03-31T20:00:03.650 回答
0

你可以试试下面的代码:

1.Sub_Category.php(Model)

public function listimg() {
    return $this->belongsTo('App\Listening');
}

2.Contoller
$sub_category = \App\Sub_Category::with('listing')->get();
于 2019-04-01T10:58:01.210 回答
0

对于自定义外键列,您为函数传递了两个附加参数,其中hasMany('Model', 'fk', 'pk')包含外键列名称和引用键列名称。

class Category extends Model
{
    protected $table = 'categories';
    public function contents(){
        return $this->hasMany('App\Content', 'sub_cat_id', 'id');
    }
}
class Content extends Model
{
    //
    protected $table = 'contents';
    public function category(){
        return $this->belongsTo('App\Category');
    }
}

 Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id');
            $table->integer('parent_id');
            $table->string('title');
            $table->timestamps();
        });

Schema::create('contents', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('app_id');
            $table->integer('cat_id');
            $table->bigInteger('sub_cat_id')->unsigned();
            $table->integer('content_type');
            $table->text('content');
            $table->text('title');
            $table->timestamps();
            $table->foreign('sub_cat_id')->references('id')->
            on('categories')->onDelete('cascade');

        });
于 2020-02-14T21:44:07.033 回答