Laravel - how get a single model instance not as collection, but single model from belongsToMany

Pet*_*ter 1 php model relation laravel laravel-5

I have this relation defined in one of my models. It is the simplest possible case.

use \App\Models\Related;

public function entities()
{
    return $this
           ->belongsToMany(Entity::class, 'entity_related', 'related_id', 'entity_id');
}
Run Code Online (Sandbox Code Playgroud)

Now, I want to create a relation which gets only one model from the table.

Current solution

我只是定义了相同的关系,但使用->take(1)。粗暴,但行得通。该解决方案的低迷之处在于,我需要做一个foreach循环以获得所需的单个模型。

use \App\Models\Entity;

public function firstOfEntities()
{
    return $this
           ->belongsToMany(Entity::class, 'entity_related', 'related_id', 'entity_id')
           ->take(1); // <---
}
Run Code Online (Sandbox Code Playgroud)

去做

如何正确定义仅获取一个(几乎任何一个)模型实例的关系,而不是创建一个集合?

理想的用法

完成上述操作后,我希望能够在foreach循环内在模板文件中使用单个模型:

@foreach($object as $o)
    <h2>{{ $o->singleEntity->name }}</h2>
    <p>{{ $o->singleEntity->description}}</p>
@endforeach
Run Code Online (Sandbox Code Playgroud)

Ken*_*rna 5

您可以定义一个访问器以获取第一个元素:

/** MyModel.php */

use \App\Models\Entity;

// Your current relationship
public function entities()
{
    return $this
       ->belongsToMany(Entity::class, 'entity_related', 'related_id', 'entity_id');
}

// the accessor
public function getFirstEntityAttribute()
{
    return $this->entities()->first();
}
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中:

/** MyModelController.php */
$model = MyModel::find(1);
$entity = $model->first_entity;
Run Code Online (Sandbox Code Playgroud)

查看此主题相关的文档