在 laravel/livewire 网站上,我读取了可能急切加载标签的数据:
$this->postList = Post
::orderBy('title')
->with('tags')
->getByTitle('%search%')
->select('id', 'post_category_id', 'title', 'slug', 'image', 'published', 'created_at', 'creator_id')
->paginate(10)
->through(function ($postItem) {
$postItem->image = (new CheckModelImage())->get($postItem->image, get_class($postItem));
return $postItem;
});
在模板文件中,我调用其他组件并传递标签参数:
@livewire('model-tag', ['id'=>$post->id, 'tags' => $post->tags], key($post->id))
如果在顶部请求中没有使用标签渴望参数,我可以通过什么方式检查它?
我尝试使用 isset 方法检查 model-ag 组件的内部:
类 ModelTag 扩展了 Component { 使用AppCommonTrait;
public int $id;
public $tags;
public $modelTaggables = [];
public function render(): View
{
return view('livewire.model-tag');
}
public function mount(int $id, ?\Illuminate\Database\Eloquent\Collection $tags = null)
{
$this->id = $id;
$this->tags = $tags;
$this->getData();
}
protected function getData(): void
{
if(isset($this->tags)) { // I CHECK HERE _ BUT IT ALWAYS VALID
$this->modelTaggables = $this->tags;
} else {
$this->modelTaggables = Taggable
->getByTaggableId($this->id)
->with('tag')
->get()
->map(function ($TaggableItem) {
return ['id' => $TaggableItem->tag_id, 'name' => $TaggableItem->tag->name];
});
}
}
}
我在资源中搜索类似whenLoaded的方法...
有吗?
"laravel/framework": "^10.48.7",
"livewire/livewire": "^3.4.10",
提前致谢!
在调用模型标签的所有请求中,您都传递参数标签。如果您的 Post 对象没有标签,它将返回一个空数组而不是 null。
所以,
isset([])
总是返回true
;
可以用空白法,
if(! blank($this->tags)) {
您可以使用 Laravel 方法
exists()
检查带有标签的帖子是否存在。
示例:
$post->tags()->exists()