Laravel与整数[]的类型PostgreSQL列的类型
我有类别
表和产品
表。在产品中
表具有 category_id
列类型 integer []
。
ex:{1,2,3}
。
我需要产品
带有类别
关系 categories.id 存在 products.category_id
我在模型 > product
:
public function category()
{
return $this->belongsTo(Category::class, \DB::raw("ANY(category_id)"), 'id');
}
否获取类别为null
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用属于许多关系。
因为整数[]类型用于保存INT数组。
尝试在这样的模型中设置它:
在您的
product(Model)
中,您将获得此关系方法:以及在您的
category(model)
中:refrence
you should use belongs to many relation.
because integer[] type is for saving arrays of ints.
try to set it in your model like this:
in your
Product(model)
you will get this relation method:And in your
Category(model)
:Refrence
您可以使用Laravel查询构建器尝试一下
You can try this using laravel query builder
首先,我认为不可能使用Laravel关系方法来做到这一点。
其次,如果您使用的是Postgres(这是一个关系数据库),则绝对应该阅读数据库归一化的基础知识。
我建议您有一个所谓的枢轴表,将您的产品链接到您的类别,看起来像这样的类别:
免责声明:您不需要为此创建模型。只需使用
PHP Artisan Make进行迁移:迁移create_categories_products_table
categories_products
此表链接您的表,这比存储的一些数组更容易处理。也许考虑一下,这并不是那么多。您可以在Laravel文档上阅读它,也可以尝试在Google上搜索枢轴表和归一化。
完成此操作时:
现在您可以使用Laravel
allavel
这样的关系:First of all, I dont think it's possible to do this with the Laravel Relationship Methods.
Second of all, if you are using Postgres, which is a relational Database, you should definitely read up on the fundamentals of database normalization.
I would recommend you have a so called pivot table, that links your products to your categories, which could look something like this:
Disclaimer: You dont need to create a Model for this. Just make a migration with
php artisan make:migration create_categories_products_table
categories_products
This table links your tables and this is much more easy to handle than some arrays stored as json.. maybe think about it, it is not that much work to do. You can read upon it on the Laravel Documentation or try searching on google for pivot tables and normalization.
When you have done that:
Now you can just use the Laravel
belongsToMany
Relationship like so:我无法关系,但是与属性我可以获得类别,
首先将类别施放到数组中,并且
它有效
I can't relation but with attribute i can get categories
firstly cast category_id to array and
and it works