[英]laravel model prevent lazy loading throw exception when using "whenLoaded()" for relation in resource
[英]Lazy loading resource in Laravel, if the method in the model does not return a relation?
你能帮忙吗,我亲爱的同事们
In Laravel for ApiResource, there is a great function $this->whenLoaded for lazy loading of model relationships https://laravel.com/docs/8.x/eloquent-resources#conditional-relationships .
我有这样一个问题,我在 model 中有一个属性,它不返回关系,而是转到数据库中的另一个表,按特定条件收集公寓,并将其全部放入数组中(底部的 phpMyAdmin 设计器)
在这种情况下,我有地址,其中的公寓由用户存储在一个单独的字段中(好吧,为了不产生太多的地址,我们有团队负责人说这是正确的做法,我们这样做了,我我是初中生,还在学习\ (ツ) /)
获取公寓的代码正在运行,看起来像这样
地址.php
public function apartments() {
return $this->clients->map(function ($item) {
return $item->apartment;
})->sort()->flatten();
}
我想制作 AdressResource 以便它也可以通过 with (或其他东西)延迟加载,以便访问 Adresss:with('apartments')->get()) 时的加载机制是这样的(但这自然会不行)。
class Address extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
"id" => $this->id,
"city" => $this->ctiy,
"street" => $this->address,
"house" => $this->house,
$this->corpus ?? "corpus" => $this->corpus,
?? this line needs to be lazy, but I can't think of any logic. --> "apartments" => $this->apartments()
];
}
}
PS 多对多关系 假设办公室将提供许多地址,在这里我认为毕竟是一对多的连接。 在这里,好像有办公室,一包地址指一个办公室,另一包指另一个办公室(嗯,简而言之,就像在邮件中一样,就像那里的一些地址,而这里的其他地址)
您应该能够将逻辑重写为关系,我想这将解决您的问题,因此您可以使用普通whenLoaded()
调用。
public function apartments() {
return $this->belongsToMany(Apartment::class, 'clients', 'apartment_id', 'client_id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.