如何在laravel中获得多对多的关系项目

时间:2016-06-03 08:34:43

标签: php html mysql laravel many-to-many

电子商店有一个数据结构:

Series -> (many to many) -> categories -> (many to many) -> products

例如,系列是"户外系列" ,类别是" T恤" ,产品是" T恤A,T恤B等......"

以下是控制器列出一个类别

中的产品
public function view($series = 0, $cat = 0, $page = 1) {
        $category = Category::find($cat);

        $totalItems = count($category->product);
        $itemsPerPage = 30;
        $currentPage = $page;
        $urlPattern = "/ums/product/view/$series/$cat/(:num)";

        $this->data['product_list'] = $category->product()->orderBy('created_at', 'desc')->skip(($page - 1) * $itemsPerPage)->take($itemsPerPage)->get();
        $this->data['paginator'] = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);
        $this->data['category'] = $category;
        $this->data['page'] = $page;
        return view('product/list')->with($this->data);
    }

现在,问题是,我想重写代码,以便不再显示一个类别,我想展示一个系列。

这意味着如果$ series = 0,那么它会在一个类别中显示产品,如果$ cat = 0,那么它会显示 multi 类别中的产品

在laravel中如何获得多类别的产品?尝试$ series-> category-> product()但没有运气,还有如何重写该功能以支持系列的显示?

非常感谢。

4 个答案:

答案 0 :(得分:5)

假设Laravel模型类 - 系列,类别和产品

对于Series Model Class,创建一个函数

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

对于类别模型类,创建一个函数

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

现在,对于给定的系列,您可以使用。轻松检索所有相关类别 简单的函数调用

$categories = $series->categories();

最后解决了在多个类别下展示产品的主要问题。

for($categories as $category)
{
     $productsOfThisCategory = $categories->products();
     //save into some other data structure, say an array $allProducts
}

$ allProducts将为特定系列提供多类别产品。

参考:Standard eloquent relationship -Many to Many

答案 1 :(得分:1)

答案 2 :(得分:1)

如果我理解正确,那么您的模型如下所示

class Series extends Model
{

    // other code

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

    // other code
}

class Category extends Model
{

    // other code

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

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

    // other code
}

class Product extends Model
{

    // other code

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

    // other code
}

进一步获取某些系列的所有产品,您需要这样做

public function view($series = 0, $cat = 0, $page = 1)
{
    if (!empty($series)) {
        $seria = Series::with(['categories' => function($query) {
            $query->with('products');
        })->find($series);
        // or may be this will work, don't know
        // Series::with('categories.products')->find($series);

        // get all caegories from seria or certain one
        if (empty($cat)) {
            $categories = $seria->categories; 
        }
        else {
            $categories = $seria->categories()->where('id', $cat)->get; 
        }

        // retrieve produts form each category and making from them collection
        $products = $categories->map(function($category) {
            return $category->products;
        })->flatten();

        // or use this approach if above not working
        /*$products = collect([]);

        foreach ($categories as $category) {
            $produts = $products->merge($category->products);
        }*/

        // do your magic
    }
    else {
        // not exactly understand what you want to do when $series is not set
    }

    // do your magic
}

答案 3 :(得分:0)

我的方法是在windows_package 'Microsoft Visual C++ 2005 Redistributable' do source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe' installer_type :custom options '/Q' end 模型中创建类似自定义关系的东西:

Serie

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Serie extends Model { public function categories() { return $this->belongsToMany('App\Category'); } public function products() { return Product::whereIn('id', function($query){ $query->select('product_id') ->from('category_product as cp') ->join('category_serie as cs', 'cs.category_id', '=', 'cp.category_id') ->where('cs.serie_id', $this->id) ; }); } } 方法将返回products()个实例。您可以在控制器中使用它,如:

Builder

这将只执行两个查询:

$serie = Serie::find($series);
$products = $serie->products()->get();
select * from `series` where `series`.`id` = ? limit 1

这也应该是可能的:

select * 
from `products` 
where `id` in (
    select `product_id`
    from `category_product` as `cp`
    inner join `category_serie` as `cs`
        on `cs`.`category_id` = `cp`.`category_id`
    where `cs`.`serie_id` = ?
)