payter/has-column-many

该包将为Laravel Eloquent模型提供添加以逗号分隔的ID关系的功能

dev-main 2022-05-20 10:10 UTC

This package is auto-updated.

Last update: 2024-09-20 15:29:54 UTC


README

您将能够通过在Eloquent模型中添加几行代码,轻松地在MySQL表中创建逗号分隔值的关联。

因此

如果您使用Laravel,并且您的表关系如下,那么这个包就适合您

Comma separated example PHP Serialized example

安装

使用Composer安装包

composer require payter/has-column-many

基本用法

使用这个包非常简单——您只需将UseColumnMany特质包含到您的模型中。

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use PayteR\UseColumnMany;

class ModelName extends Model
{
    use UseColumnMany;

    public function relateds()
    {
        return $this->hasColumnMany(RelatedModel::class, 'related_ids');
    }
}

您可以像调用其他Eloquent关系一样调用它

use App\Models\ModelName;
 
$relateds = ModelName::find(1)->relateds;
 
foreach ($relateds as $related) {
    //
}

高级用法

多列

您甚至可以从多个列中连接ID!这很简单——只需将列名数组作为第二个参数传递

return $this->hasColumnMany(RelatedModel::class, ['related_ids', 'another_column_ids']);

JSON和序列化ID

您不需要做任何事情,它将自动假设它是逗号分隔的、JSON还是序列化的。

您可以