用两个模型循环遍历Laravel模型


Loop through Laravel model with two models

我正在努力找出解决这个问题的最佳方法。我有两个模型,一个类别和另一个库存。我想搜索一个类别和每个产品(库存),匹配该类别模型显示在一个搜索结果限制为20页。我可以从$cat中获得$类别,没有问题。我只是不确定最简单的方法来循环每个库存模型。Eloquent有简单的方法吗?我也不知道这会对分页有什么影响

public function showCategory($cat) {
    $category = Categories::where('category', '=', $cat)->get();
    $inventory = Inventory::where('sku', '=', $category)->paginate(20);
    $image = Images::where('sku', '=', $category->sku)->first();
    if (is_null($inventory)) {
        return App::abort(404);
    }
    return View::make('inventory.category', array('pageTitle' => $category->category, 'inventory' => $inventory, 'category' => $category, 'image' => $image));
}

例如,如果类别中有足球,我希望类别模型中相同sku的每个产品(库存)显示为结果

id name sku category
1  Blah  1234  soccer
2  Blah  2222  bball
3  Blah  3333  baseball
4  Blah  4444  soccer
5  Blah  5555  soccer

我想要收集的结果将显示类似于库存表

库存

id    name   sku   more_stuff_ineed
1454   Blah  1234  blah
43546  Blah  4444  blah
54567  Blah  5555  blah

基本上只是确保您的关系定义正确(我个人将库存模型命名为Product,因为您正在处理产品,而不是库存)。或者可能是InventoryItem..)

假设你有一个Category模型和一个Product模型;您可以这样定义您的模型:

class Product extends Eloquent {
    public function category()
    {
        return $this->belongsTo('Category');
    }
}
class Category extends Eloquent {
    public function product()
    {
        return $this->hasMany('Product')
    }
}

这里假设您的产品在其其他数据中有一个名为"category_id"的列,这是它与类别相关的方式。在这种情况下,我们假设是"一对多"关系。如果您决定要一个产品属于多个类别,则需要调查"多对多"关系,并需要额外的第三个表来存储这些关系。

一旦你像这样定义了你的模型,你就可以像这样查询属于一个类别的产品:

$products = Product::where('category_id', $catId)->paginate(20);

确保你阅读了这里所示的雄辩关系的文档,并充分理解不同类型的关系。你需要对它有一个可靠的处理,以确保你的表和模型被正确地定义,当然,你的代码使用正确的语法来查询它们。

注。我注意到你给模特取的名字都是复数。通常,Eloquent期望的命名约定是使用PascalCase的单数模型和复数(小写)表名。因此,您的底层sql表为我的例子将被称为"类别"answers"产品",而模型将被称为"产品"answers"类别"。