Laravel Livewire 从字符串中获取关系数据
Laravel Livewire Get Relation Data From String
我正在创建一个动态呈现数据的 Livewire 数据 table 组件。但是我在渲染关系数据时遇到了一些问题。
Subscription.php (Model)
class Subscription extends Model
{
...
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
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
我正在创建一个动态呈现数据的 Livewire 数据 table 组件。但是我在渲染关系数据时遇到了一些问题。
Subscription.php (Model)
class Subscription extends Model
{
...
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
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