byancode/belongs-to-one

Belongs To One Laravel 9 关联类

v2.0.3 2022-07-17 15:48 UTC

This package is auto-updated.

Last update: 2024-09-17 20:33:10 UTC


README

Travis CI

基于 Belongs To Many 关联。返回单个模型而不是模型集合。

安装

composer require byancode/belongs-to-one

用法

BelongsToOne 关联几乎与标准 BelongsToMany 相同,除了它返回单个模型而不是模型集合,并且当数据库中没有相关模型时返回 null(在这种情况下,BelongsToMany 返回空集合)。在你的模型中包含 Byancode\Database\Eloquent\Relations\BelongsToOneTrait 并使用 BelongsToOne 关联。

示例

<?php

namespace App\Models;

use App\Models\Group;
Use Illuminate\Database\Eloquent\Model;
use Byancode\Database\Eloquent\Relations\BelongsToOneTrait;

class Record extends Model
{
    use BelongsToOneTrait;
    
    public function group()
    {
        return $this->belongsToOne(Group::class);
    }
}

然后像使用任何其他关系一样使用它

$record = Record::with('group')->first();

测试

./vendor/bin/phpunit