【问题标题】:Search and many to many relationships搜索和多对多关系
【发布时间】:2019-05-10 04:56:57
【问题描述】:

我有帖子模型和标签模型我需要进行搜索查询,以便用户输入标签,然后该函数获取此标签并显示所有相关帖子,因此它是多对多关系帖子属于许多标签并且标签属于许多帖子,所以我声明了关系船,但我找不到一种方法使 where 与关系船的子句很明显我不知道在模型名称和关系函数中放什么

这是我的搜索功能

public function search()
{
    $q = Input::get ( 'q' );
    $posts = post::where('tag_name','LIKE','%'.$q.'%')->tags()->get;
    dd($posts);
    if(count($posts) > 0)
        return view('guest.blog.search_result' , ['title' => 'Resaults'])->withDetails($posts)->withQuery ( $q );
    else return view ('guest.blog.no_resault' , ['title' => 'Resaults'])->withMessage('No Details found');
}

我的帖子模型

public function tags()
{
   return $this->belongsToMany('\Conner\Tagging\Model\Tagged');
}

我的标签模型(来自 rtconner 包)

这个关系来自原包

public function tag()
{
    $model = $this->taggingUtility->tagModelString();
    return $this->belongsTo($model, 'tag_slug', 'slug');
}

我声明了这种关系

public function posts()
{
    return $this->belongsToMany('App\Post');
}

我的问题是如何使搜索查询正常工作而不会出错

注意:有一个搜索字段,用户将只写标签,所以我应该输入这个标签,然后查找其对应的帖子 然后我会把它展示给用户

编辑

我的搜索功能

public function search()
      {
          $q = Input::get ( 'q' );

// 我使用 get 是因为我想要属于同一标签的所有帖子 $posts = Tagged::where('tag_name','LIKE','%'.$q.'%')->with('posts')->get(); dd($帖子); 如果(计数($posts)> 0) return view('guest.blog.search_result' , ['title' => 'Results'])->withDetails($posts)->withQuery ( $q ); else return view ('guest.blog.no_result' , ['title' => 'Results'])->withMessage('No Details found'); }

我的标签和帖子模型是一样的

我在数据库中添加了一个名为 post_tagged 的​​表,其中我有两列 post_id 和 tagged_id。

所以关系会通过这个表发生,如果你没有创建它会抛出 SQL 状态错误

【问题讨论】:

    标签: php laravel relationship backend


    【解决方案1】:

    据我了解,您正在尝试根据帖子所属的标签查询帖子。

    你做错的第一件事,除非你在你的 post 表上有一个 tag_name 列,否则你正在查询 post 表 tag_name 而不是 tag 表。

    public function search()
    {
        $q = Input::get ( 'q' );
    
        //Use first instead of get incase of multiple results
        $tag = Tag::where('tag_name','LIKE','%'.$q.'%')->with('posts')->first();
    
        return view('guest.blog.search', compact('tag','q'));
    }
    

    您需要做的是根据标签的名称查询标签。然后eager load 发布所有标签。您也不需要控制器中的条件语句。您可以在刀片模板中添加条件语句,如下所示:

    @if($tag->count())
        @if($tag->post->count())
            @foreach($tag->post as $post)
                {{$post->title}}
            @endforeach
        @else
            <h1>No posts found
        @endif
    @else
        <h1>There was no tag. {{$q}}</h1>
    @endif
    

    【讨论】:

    • 谢谢你给了我提示,虽然我改变了你所说的几乎一半,但它起作用了^^
    猜你喜欢
    • 1970-01-01
    • 2013-09-30
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多