ghanuz/relations

使用逗号分隔的外键或使用FIND_IN_SET mysql函数创建Eloquent关系。

3.6 2024-02-25 10:08 UTC

This package is auto-updated.

Last update: 2024-09-25 11:42:03 UTC


README

设置与包含逗号分隔值作为外键的表的关系

安装

使用composer获取包

composer require ghanuz/relations

1.

您必须扩展GhanuZ\Model类而不是Illuminate\Database\Eloquent\Model

<?php

namespace App;

use GhanuZ\Model;

class Test extends Model
{
    //
}

您还可以使用特质而不是扩展模型类

类似于Laravel,Users模型没有扩展Model类。因此,您可以使用traitGhanuZ\FindInSet\FindInSetRelationTrait

示例

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use GhanuZ\FindInSet\FindInSetRelationTrait;

class User extends Authenticatable
{
    use Notifiable, FindInSetRelationTrait;

    public function city ()
    {
        return $this->FindInSetOne( 'App\City', 'city_ids', 'id', 1);
    }

    public function state ()
    {
        return $this->FindInSetOne( 'App\State', 'city_ids', 'id', 2);
    }

    public function country ()
    {
        return $this->FindInSetOne( 'App\Country', 'city_ids', 'id', 3);
    }

    public function hobbies ()
    {
        return $this->FindInSetMany( 'App\Hobbies', 'hobbies_id', 'id');
    }

}

要创建HasMany关系,您必须编写如下:

public function order_product (){
    return $this->FindInSetMany( CLASS_NAME, FOREIGN_KEY, LOCAL_KEY);
}

要创建HasOne关系,您必须编写如下:

public function order_product (){
    return $this->FindInSetOne( CLASS_NAME, FOREIGN_KEY, LOCAL_KEY);
}

您还可以传递第4个参数来检测FIND_IN_SET中的位置

如果您有一个address表模式,并且像city_ids那样存储。

现在,您只想找到city_id,您将这样做: select * from address where FIND_IN_CITY( 2, city_ids ) = 1;// 这里 $index = 1

对于state_idselect * from address where FIND_IN_CITY( 1, city_ids ) = 2;// 这里 $index = 2

对于country_idselect * from address where FIND_IN_CITY( 5, city_ids ) = 3;// 这里 $index = 3

第4个参数是可选的

public function order_product (){
    return $this->FindInSetMany( CLASS_NAME, FOREIGN_KEY, LOCAL_KEY, Number);
}

从版本v3开始添加了对数组转换的支持。

从版本v3开始,您还可以使用Laravel框架提供的自定义转换来操作逗号分隔值。如果您使用Laravel的casts将带有逗号值的字符串转换为数组,则此包也支持它来检索相关表数据。

示例


/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
    'FIELD' => CUSTOM_CLASS::class,
];


/**
*
* To retrive array of relational tables 
*
*/
public function order_products ()
{
    return $this->FindInSetMany( CLASS_NAME, FOREIGN_KEY, LOCAL_KEY, Number);
}

/**
*
* To retrive single data of the relational table
*
*/
public function order_product ()
{
    return $this->FindInSetOne( CLASS_NAME, FOREIGN_KEY, LOCAL_KEY, Number);
}