tusimo/embed-relation

laravel 的关系

v0.3 2018-11-30 02:13 UTC

This package is not auto-updated.

Last update: 2024-09-15 05:34:04 UTC


README

embed-relation 最新稳定版本 总下载量

embedsMany 扩展了 Laravel 的 ORM,允许添加缺少的新关系。

安装

需要 PHP 5.6+。

要获取 embedsMany 的最新版本,只需使用 Composer 引入项目。

$ composer require tusimo/embed-relation

当然,您也可以手动更新 require 块并运行 composer update

{
    "require": {
        "tusimo/embed-relation": "^0.1"
    }
}

用法

在您的 eloquent 模型类中添加以下行。当我们有一个作为数据列的 json 字符串列时。我们支持虚拟列和可以使用 cast。支持一些新的 cast,'integer_array', 'string_array', 'float_array', 'bool_array'。

class User extends Model {
    use \Tusimo\Eloquent\Traits\EmbedsRelation;
    use \Tusimo\Eloquent\Traits\CastAttributes;
    
    protected $virtualColumnMaps = [
        'data' => [
            'address' => 'home_address',//you can rename the column
            'follower_ids'
        ],
        //'more_json_data' => [],
    ];
    
    protected $casts = [
        'book_ids' => 'integer_array',
        'home_address' => 'string',
        'follower_ids' => 'integer_array',
    ];
    ...
}

示例

考虑用户有几种喜欢的书,书 ID 只存储在用户表的 book_ids 列中。我们希望这个列可以通过关系来加载。所以我们可以这样做。我们有这样的用户表。

和这样的书籍表

class User extends Model {
    use \Tusimo\Eloquent\Traits\EmbedsRelation;

    public function books () {
        return $this->embedsMany(Book::class);
    }
}

如果我们想获取书籍,我们可以使用 $user->books。现在我只是完成了获取关系数据。接下来我将做保存的事情和反向关系。

现在我们可以这样访问数据。

    $user->home_address = 'HA';
    $user->follower_ids = [1,2,3,4];
    $user->save();
    foreach($user->follower_ids as $followerId) {//which now is array type
        echo $followerId;
    }
    if($user->isVirtualDirty('home_address')) {
        //detect virtual column is dirty or not 
        dd($user->getVirtualDirty());
    }

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件