提问者:小点点

在模型及其关系中搜索并对结果分页


因此,我正在使用Laravel/MySQL构建一个电子商务站点,与产品相关的表如下:“产品”、“属性”、“分类法”和“标签”。当用户键入关键字搜索产品时,我想用一个查询搜索所有4个表以获得所需的产品,然后我想使用Laravel paginate函数对结果进行分页,现在如何在一个查询中完成?也许会有人加入?

这里是我的数据库表的关系,对于我的模型,它的定义如下:

class Product extends Eloquent {
    ...
    public function taxonomies() {
        return $this->belongsToMany('Taxonomy', 'product_taxonomy', 'product_id', 'taxonomy_id');
    }
    ...
    // Same goes for attributes and labels
    public function reviews() {
        return $this->hasMany('Review', 'product_id');
    }
}

共3个答案

匿名用户

也许你想要这样的东西:

$products = Product::where('name', 'LIKE ', '%' . $keyword . '%');

$products = $products->orWhereHas('attributes',
    function ($query) use ($keyword) {
        $query->where('name', 'LIKE ', '%' . $keyword . '%');
    }
);
$products = $products->orWhereHas('taxonomies',
    function ($query) use ($keyword) {
        $query->where('name', 'LIKE ', '%' . $keyword . '%');
    }
);
$products = $products->orWhereHas('tags', 
    function ($query) use ($keyword) {
        $query->where('name', 'LIKE ', '%' . $keyword . '%');
    }
);


$products = $products->paginate(10);

现在,您可以查看产品名称和关系名称(标记、分类法和属性),并对10个产品进行分页。

匿名用户

你可以这样试试

$data = DB::table('products')
->join('attributes', 'products.attributes_id', '=', 'attributes.id')
->join('taxonomies', 'products.taxonomies_id', '=', 'taxonomies.id')
->join('tags', 'host_vulnerabilities.tags_id', '=', 'tags.id')
->where('products.id', '=', $id)
->select('products.id', 'attributes.name') //all required fields
->paginate(15);

我刚刚添加了示例示例。请根据您的要求更新代码

匿名用户

为此使用UNION

SELECT product_id, product name FROM Products WHERE keyword = 'my_keyword' UNION 
SELECT product_id, product name FROM Attributes WHERE keyword = 'my_keyword' UNION
..... Same for other tables

此外,它将过滤掉重复的结果,因为UNION作为UNION DISTINCT工作。但是如果你给我们提供一个模式或一些数据库结构,可以提供一个更好的解决方案。

对于Laravel,这可能有效。您可以创建视图并查询视图而不是实际的表,或者手动创建分页器:

$page = Input::get('page', 1);
$paginate = 10;
$w1 = 'my_keyword';

$first = DB::table('products')->where('attribute', 'like', '"%'.$w1.'%"');
$second = DB::table('attributes')->where('attribute', 'like', '"%'.$w1.'%"');
$third = DB::table('taxonomies')->where('attribute', 'like', '"%'.$w1.'%"');
$fourth = DB::table('tags')->where('attribute', 'like', '"%'.$w1.'%"');

$union1 = $first->union($second);
$union2 = $third->union($union1);
$union3 = $fourth->union($union2);
$union3->get();

$slice = array_slice($union3, $paginate * ($page - 1), $paginate);
$result = Paginator::make($slice, count($union3), $paginate);

return View::make('yourView',compact('result'));