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

时间:2014-09-29 13:38:19

标签: mysql search laravel laravel-4 eloquent

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

enter image description here

在这里,我的数据库表的关系,就我的模型而言,它的定义如下:

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 个答案:

答案 0 :(得分: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产品。

答案 1 :(得分:1)

使用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,您可以创建视图并查询视图而不是实际表,或手动创建Paginator:

$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'));

答案 2 :(得分:1)

您可以尝试这样

$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);

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