我正在开发一个具有以下 Eloquent 模型的 laravel 应用程序
- Product hasMany('App/Sku','products_id')
- Sku belongTO('App/Product')
我有一个 Controller “ProductController”,其中提供了以下代码
public function index()
{
$products = Product::all();
foreach($products as $product){
$products_id = $product->products_id;
}
}
我正在公开 RESTfull API,它将允许我的用户获取所有产品详细信息(包括 SKU、运输类型等)。
假设我有一个 API GET :/products
获取所有产品详细信息的代码如下所示
public function index()
{
$products = Product::all();
foreach($products as $product){
$products_id = $product->products_id;
$skus_data = Product::find($products_id)->skus;
}
// Now I have both the product details + skus which I can bundle into an array/json.
}
现在我的问题是,这个逻辑是否正确?在这种情况下,所有逻辑都在 Controller 中,因为我使用的是 Eloquent 模型,我为每个表都有一个模型,并且在其中定义了关系。有没有一种方法可以获得产品/相关模型的所有详细信息(产品详细信息(在表 1 中)+ Sku 详细信息(在表 2 中))而不是使用下面的
foreach($products as $product){
$products_id = $product->products_id;
$skus_data = Product::find($products_id)->skus;
}
我对 Laravel 开发和 Eloquent 模型还很陌生。我将使用存储库模式进行开发,在这种情况下,aboe 逻辑(Product+Sku 组合)驻留在何处。
请帮忙。
最佳答案
是的,您可以获得产品和 SKU 的详细信息,而无需使用 eager loading 对每个产品进行一次额外查询。 (这被称为典型的 N+1 查询问题,其中 N 是产品的数量)
假设您的 Product
和 Sku
模型模型之间的关系是:
产品
public function skus()
{
return hasMany('App/Sku','products_id');
}
要获取产品数据和 sku 数据,您可以使用 with
方法。在你的 Controller 中:
Controller
$products = Product::with('skus')->get();
然后,在您的 View 中,您可以通过以下方式获取信息:
查看
foreach ($products as $product)
{
//$product->skus is a collection of Sku models
dd( $product->skus );
}
对于存储库问题:如果您想使用存储库,您可以将代码的 Eloquent 访问部分放在存储库中。因此,例如,您可以在存储库中使用此方法:
产品库
public function getProductsData()
{
//access eloquent from the repository
return Product::with('skus')->get();
}
然后您可以在您的 Controller 中使用您的存储库:
Controller
//inject the repository in the controller
public function __construct( ProductRepository $productRepo )
{
$this->productRepo = $productRepo;
}
//use the injected repository to get the data
public function index()
{
$products = this->productRepo->getProductsData();
}
关于php - Laravel Eloquent 模型如何从关系表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34082264/