如何修复 Laravel 预加载不适用于自定义外键

How to fix Laravel eager loading not working with custom foreign key

Listing 和 Sub_Category 是一对多的关系。房源属于一个 sub_category,而 sub_category 有多个房源。

我的列表中有一列 table '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 clause' 中的未知列 'listings.sub__category_id'。

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

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

我认为你应该这样设置:

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 document在set Relationships中我们先设置foreign_key然后local_key这样(示例来自 laravel 网站):

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

您可以试试下面的代码:

1.Sub_Category.php(Model)

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

2.Contoller
$sub_category = \App\Sub_Category::with('listing')->get();

对于自定义外键列,您已通过外键列名称和引用键列名称为函数 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');

        });