Search code examples
laraveleloquenteager-loadinglaravel-5.6

laravel eloquent generates wrong query when eager-loading


I have the database table like this:

id, title, description (NULL), parent_product_template_id (NULL)

I have the foreign key parent_product_template_id which references the id column from the same table.

in the controller I done the query:

$productTemplates = ProductTemplate::whereNull('parent_product_template_id')->get();

and compacted the results and passed them to the view.

in the view I have this forelse loop:

@foreach($productTemplates as $productTemplate)
   $productTemplate->childs
@endforeach

where the ProductTemplate model looks like this.

class ProductTemplate extends Model
{
  public $timestamps = false;
  public function parent()
  {
    return $this->belongsTo('App\Models\ProductTemplate');
  }
  public function childs()
  {
    return $this->hasMany('App\Models\ProductTemplate');
  }
}

finally the problem is that when running the code, I get this error message

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_templates.product_template_id' in 'where clause' (SQL: select * from `product_templates` where `product_templates`.`product_template_id` = 1 and `product_templates`.`product_template_id` is not null) (View: E:\wamp\www\SyriaShop\resources\views\admin\product-template\index.blade.php)

why and how it used such a strange key 'product_template_id' rather than the real 'id' column


Solution

  • If you use non-standard Foreign Keys in the database then you need to explicitly state them in the relationship.

    Defining foreign keys in the migrations does not fix eloquent relationships.

    public function parent()
    {
        return $this->belongsTo('App\Models\ProductTemplate','parent_product_template_id','id');
    }