我正在努力找出解决这个问题的最佳方法。我有两个模型一个类别和另一个库存。我想要搜索一个类别,每个与该类别模型匹配的产品(库存)显示在搜索结果中,限制为20页。我可以从$ cat获得$ category没有问题。我只是不确定使用Inventory模型遍历每个方法的最简单方法。 Eloquent有什么容易的吗?我也不知道这将如何影响paginate
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
答案 0 :(得分:0)
基本上只是确保你的关系被正确定义(我个人会命名库存模型产品,因为你正在处理产品,而不是库存..或者可能是InventoryItem ..)
因此,假设您有一个分类模型和一个产品模型;你会像这样定义你的模型:
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 Relationships的文档,显示为here,并完全了解不同类型的关系。您需要有一个可靠的句柄来确保正确定义表格,以及您的模型,当然您的代码使用正确的语法来查询它们。
P.S。我注意到你用复数形式命名了你的模型。通常,Eloquent期望的命名约定是具有PascalCase的单数模型和多个(小写)表名。因此,我的示例的底层sql表将被称为" categories"和"产品",而模型将被称为"产品"和"类别"。