使用spatie / laravel-tags插件获取相关项目

时间:2018-10-18 13:55:32

标签: laravel-5 tags

在我的Laravel 5.7应用中使用spatie/laravel-tags插件(https://docs.spatie.be/laravel-tags/v2/basic-usage/using-tags)。

我的Vote模型(app/Vote.php)具有标签:

<?php

namespace App;

use DB;
use App\MyAppModel;
...
use Spatie\Tags\Tag as SpatieTag;
use Spatie\Tags\HasTags;

class Vote extends MyAppModel
{
    use HasTags;

    protected $table = 'votes';
    protected $primaryKey = 'id';

然后我尝试通过Tag来获取所有相关的投票,这些投票都有此标签,例如:

    $activeTag = Tag::containingSlug($tag_slug)->first();
    $tagRelatedVotes= Vote::withAnyTags( [$activeTag->slug], 'votesTagType' )->get();

但是tagRelatedVotes为空,然后看下面的sql跟踪:

   SELECT * 
    FROM `tags` 
    WHERE LOWER(JSON_EXTRACT(slug, "$.en")) like '"%animals%"' limit 1 


   SELECT * 
    FROM `tags` 
    WHERE `name`->'$."en"' = '{"en": "animals"}'     AND `type` = 'votesTagType' limit 1 


   SELECT * 
    FROM `votes` 
    WHERE 
    EXISTS (  SELECT * 
    FROM `tags` 
    INNER JOIN `taggables` on `tags`.`id` = `taggables`.`tag_id` 
    WHERE `votes`.`id` = `taggables`.`taggable_id`     AND `taggables`.`taggable_type` = 'App\Vote'     AND `id` in ('')) 

第一条语句找不到行,但是第二条语句什么也没找到,这很奇怪为什么在请求中使用名称字段? 因此,第三条语句无效。哪种方法有效?

已修改的块#2: 感谢您的反馈意见! 正如您所写,我尝试过,但结果却空虚。 我对sql的跟踪见下:

   SELECT * 
    FROM `tags` 
    WHERE LOWER(JSON_EXTRACT(slug, "$.en")) like '"%thriller%"' limit 1 


   SELECT * 
    FROM `tags` 
    WHERE `name`->'$."en"' = '{"en": "Thriller"}'     AND `type` = 'votesTagType' limit 1 


   SELECT * 
    FROM `votes` 
    WHERE 
    EXISTS (  SELECT * 
    FROM `tags` 
    INNER JOIN `taggables` on `tags`.`id` = `taggables`.`tag_id` 
    WHERE `votes`.`id` = `taggables`.`taggable_id`     AND `taggables`.`taggable_type` = 'App\Vote'     AND `id` in ('')) 

第一个语句返回1行,但是第二个语句什么也没有返回,但是我有1行名称为'Thriller'和type ='votesTagType'。 我不确定

`name`->'$."en"' = '{"en": "Thriller"}' 

意味着,这超出了我的mysql经验。 CXan是一些mysql还是这个插件选项? 我有:

   SELECT version() : 5.7.23-0ubuntu0.18.04.1

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须将标记的name传递给withAnyTags()方法。 docs

$activeTag = Tag::containingSlug($tag_slug)->first();
$tagRelatedVotes= Vote::withAnyTags( [$activeTag], 'votesTagType' )->get();