我正在创建一个动态呈现数据的Livewire数据表组件。但是我在渲染关系数据时遇到了一些问题。
Subscription.php (Model)
class Subscription extends Model
{
...
public function user()
{
return $this->belongsTo('AppModelsUser');
}
}
LivewireComponent.php
class SubscriptionTable extends Component
{
...
public $columns =[
[
"name" => "User ID",
"field" => "user_id",
"sortable" => false,
],
[
"name" => "Owner",
"field" => null,
"sortable" => false,
"relation" => "user->name"
]
];
}
livewire-component.blade.php:
...
@if(isset($columns['relation']))
{{ dd($subscription->{$columns['relation']}) }} //return null
@else
{{ dd($subscription->{$columns['field']}) }} //return User model
@endif
是否有任何解决方案或任何工作区来检索用户名?
可以使用data_get从关系中获取数据。
class SubscriptionTable extends Component
{
...
public $columns =[
[
"name" => "User ID",
"field" => "user_id",
"sortable" => false,
],
[
"name" => "Owner",
"field" => null,
"sortable" => false,
"relation" => "user.name"
]
];
}
livewire-component.blade.php:
...
@if(isset($columns['relation']))
{{ dd(data_get($subscription,$columns['relation'])) }}
// with get the value like $subscription['user']['name']
// you can also pass the 3rd argument as default value
@else
{{ dd($subscription->{$columns['field']}) }} //return User model
@endif