Laravel:在每个select查询后执行集合格式化
Laravel: Perform collection formatting after each select query
假设以下数据库 tables:
Clients Users
| Id | name | user_id | | ID | name |
| -- | ----- | ------ | | -- | ------ |
| 1 | NULL | 1 | | 1 | David |
| 2 | Peter | NULL |
并非每个 client 都会自动成为 user,但用户可能拥有客户帐户。用户 table 仅包含注册用户,如果用户是客户(不一定是),则会创建客户帐户。
我已经成功地建立了这些 table 之间的关系是 Laravel。 Eloquent 查询工作正常,例如:
clients.php
public function userAcc() {
return $this->hasOne('User', 'id', 'user_id');
}
user.php
public function clientAcc() {
return $this->hasOne('Clients', 'user_id', 'id');
}
问题是当我查询这些 tables:
Clients::with('userAcc')->get()
鉴于我必须做出很多假设,例如:
@if($client->userAcc)
{!! $client->userAcc->name !!}
@else
{!! $client->name !!}
@endif
laravel 中是否有任何变通方法允许我在每个 select 查询中格式化集合?类似 Accessor 的东西,但在整个集合中,所以我将能够在视图中做这样的事情:
{!! $client->realname !!}
并且它写入来自特定 table 的客户端名称。
非常感谢任何建议
你可以为此创建一个方法:
public function getName()
{
return $this->userAcc?$this->userAcc->name:$this->name;
}
在你的 blade 中调用函数:
{{$client->getName()}}
这是 Laravel 实现此目的的方法:
class Client extends Model {
public $appends = ['realname'];
public function userAcc() {
return $this->hasOne('User', 'id', 'user_id');
}
public function getRealnameAttribute(){
return $this->userAcc? $this->userAcc->name : $this->name;
}
现在可以通过 $client->realname 访问它,并将包含在 $client->toJson() 和 $client->toArray()
假设以下数据库 tables:
Clients Users
| Id | name | user_id | | ID | name |
| -- | ----- | ------ | | -- | ------ |
| 1 | NULL | 1 | | 1 | David |
| 2 | Peter | NULL |
并非每个 client 都会自动成为 user,但用户可能拥有客户帐户。用户 table 仅包含注册用户,如果用户是客户(不一定是),则会创建客户帐户。
我已经成功地建立了这些 table 之间的关系是 Laravel。 Eloquent 查询工作正常,例如:
clients.php
public function userAcc() {
return $this->hasOne('User', 'id', 'user_id');
}
user.php
public function clientAcc() {
return $this->hasOne('Clients', 'user_id', 'id');
}
问题是当我查询这些 tables:
Clients::with('userAcc')->get()
鉴于我必须做出很多假设,例如:
@if($client->userAcc)
{!! $client->userAcc->name !!}
@else
{!! $client->name !!}
@endif
laravel 中是否有任何变通方法允许我在每个 select 查询中格式化集合?类似 Accessor 的东西,但在整个集合中,所以我将能够在视图中做这样的事情:
{!! $client->realname !!}
并且它写入来自特定 table 的客户端名称。
非常感谢任何建议
你可以为此创建一个方法:
public function getName()
{
return $this->userAcc?$this->userAcc->name:$this->name;
}
在你的 blade 中调用函数:
{{$client->getName()}}
这是 Laravel 实现此目的的方法:
class Client extends Model {
public $appends = ['realname'];
public function userAcc() {
return $this->hasOne('User', 'id', 'user_id');
}
public function getRealnameAttribute(){
return $this->userAcc? $this->userAcc->name : $this->name;
}
现在可以通过 $client->realname 访问它,并将包含在 $client->toJson() 和 $client->toArray()