Laravel relationship based on custom attribute not working both directions

て烟熏妆下的殇ゞ 提交于 2021-01-29 10:53:33

问题


Models Product and Category.

Product model has this custom attribute: getCategoryIdAttribute(). because the way to get category id is a bit complex.

With that attribute I can define the relationship (Product -> Category):

public function category()
{
    return $this->belongsTo(Category::class, 'category_id', 'id');
}

This relationship works fine!

But now on the Category model:

public function products()
{
    return $this->hasMany(Product::class, 'category_id', 'id');
}

If I use this relationship it fails on SQL.

Example on tinker:

Product::first()->category; // Works!
Category::first()->products; // Undefined column: 7 ERROR:  column products.category_id does not exist

Why when I use the relationship Product -> Category works but Category -> Products doesn't?

来源:https://stackoverflow.com/questions/64483032/laravel-relationship-based-on-custom-attribute-not-working-both-directions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!