【问题标题】:Search with Relationship - Laravel 5.3使用关系搜索 - Laravel 5.3
【发布时间】:2017-04-16 15:17:47
【问题描述】:

我正在开发一个搜索功能,用户可以在其中输入名称。这是我正在做的查询:

   public function api(Request $request)
    {
        $query = request()->get('query');

        $results = Listing::searchAndCache($query);

        return $results;
    }

这很符合:

 public static function searchAndCache($query)
    {
        return self::where('name','like','%'.$query.'%')->where('live',true)->paginate(15);
    }

我还需要与此查询一起搜索“位置”,问题在于它位于不同的表中。模型名称是位置。我的问题是如何将模型位置附加到此查询?

理想情况下,我想为查询执行此操作:

 public static function searchAndCache($query)
    {
        return self::where('name','like','%'.$query.'%')->where('region','like','%'.$query.'%')->where('live',true)->paginate(15);
    }

【问题讨论】:

  • 对了,在你的$query里,不是request()->get('query);,应该是这个:$request->get('query);
  • 不,我可以这样用。
  • 我知道你可以,但是你正在实例化请求,为什么不使用它呢?只是说。
  • 试试这个:你可以在你的数据透视表中添加第三个字段,这将是你另一个表中字段的外键,这样你就可以方便地访问它。跨度>

标签: laravel model relationship laravel-5.3


【解决方案1】:

对于搜索,您可以使用 searchable 特征。所以你可以这样做:

Listing::where('live',true)->search($query)->paginate(15);

如果列表和位置之间有关系,你可以使用 Laravel 的 realations 来做这样的事情

Listing::where('live',true)
         ->search($query)
         ->location
         ->search($query2)
         ->paginate(15);

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多