[英]How to get only one note from relation belongsToMany?
I just have a table that has relation belongsToMany, BUT it was a mistake by developer so I can not change this structure SO I need to get only first().我只有一个与 belongsToMany 有关系的表,但这是开发人员的错误,所以我无法更改此结构,所以我只需要获取 first()。 However, when I take only first it return empty array but I need in object
但是,当我只首先返回空数组时,但我需要 object
$animals = Cat::query()->with(['types' => function($query) {
$query->first(); //wrong
}])
So how I can get only first?那么我怎么才能得到第一呢? Because I need to order by this field and I can't because it is array
因为我需要按这个字段排序,但我不能,因为它是数组
you can do this in two ways:你可以通过两种方式做到这一点:
1- using hasOne relation: 1- 使用 hasOne 关系:
class Cat {
public function firstType() {
return $this->hasOne(Type::class, 'type_id', 'id')->latest();
}
}
2-using staudenmeir/eloquent-eager-limit 2-使用 staudenmeir/eloquent-eager-limit
after installing it you can write:安装后你可以这样写:
class Cat extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
public function firstType() {
return $this->hasMany(Type::class, 'type_id', 'id')->latest()->limit(1);
}
}
class Type extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
// ......
}
the advantage of HasEagerLimit
trait is that you can limit the result not only to one but any number you want... HasEagerLimit
特性的优点是您不仅可以将结果限制为一个,还可以将结果限制为任何您想要的数字......
now you can write:现在你可以写:
$animals = Cat::query()->with('firstType');
You can add a attribute getter and set up into appends attribute.您可以添加属性 getter 并设置为附加属性。 follow bellow example:
按照下面的例子:
class Cat {
protected $appends = ['type'];
public function getTypeAttribute() {
// return the first element from your array of the belongsToMany relationship if it exists
return isset($this->types[0])? $this->types[0] : null;
}
}
That's important to remember this method will bring just one type.
重要的是要记住此方法只会带来一种类型。 If you want to get the same type everytime, you create a diferente table where the cat table has the type_id column.
如果你想每次都获得相同的类型,你可以创建一个不同的表,其中 cat 表有 type_id 列。
obs: Sorry for my english, it's still in working progress. obs:对不起我的英语,它仍在工作中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.