php Laravel eloquent 模型如何从关系表中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34082264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:43:49  来源:igfitidea点击:

Laravel eloquent model how to get data from relationship's table

phplaravellaravel-5eloquentrepository-pattern

提问by Ajeesh

I am developing a laravel application which has the following eloquent models

我正在开发一个 Laravel 应用程序,它具有以下雄辩的模型

  • Product hasMany('App/Sku','products_id')
  • Sku belongTO('App/Product')
  • 产品 hasMany('App/Sku','products_id')
  • Sku属于('应用程序/产品')

I have a controller 'ProductController' where the following code is available

我有一个控制器“ProductController”,其中提供了以下代码

public function index()
{    
    $products = Product::all();
    foreach($products as $product){
            $products_id = $product->products_id;
    }
}

I am exposing RESTfull API which will allow my users to get all product details (including skus, shipping types etc..).

我正在公开 RESTfull API,它将允许我的用户获取所有产品详细信息(包括 skus、运输类型等)。

Suppose if I have an API GET : /products

假设我有一个 API GET : /products

The code which fetches all the product details will be some what the following

获取所有产品详细信息的代码如下

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.
}

Now my question is , is this logic proper? In this case all the logics are in the controller since im using eloquent models I have a model for each table and the relationships are defined in it. Is there a way I can get all the details of a product/associated model (Products details (in table 1)+ Sku details (in table 2)) rather than using the below

现在我的问题是,这个逻辑正确吗?在这种情况下,所有逻辑都在控制器中,因为我使用雄辩的模型,我为每个表都有一个模型,并且在其中定义了关系。有没有一种方法可以获得产品/关联模型的所有详细信息(产品详细信息(在表 1 中)+ Sku 详​​细信息(在表 2 中)),而不是使用下面的

foreach($products as $product){
    $products_id = $product->products_id;
    $skus_data = Product::find($products_id)->skus;
}

I am pretty new to laravel development and eloquent models. I will be using repository pattern for the development and in that case where does the aboe logic (Product+Sku combining) resides.

我对 Laravel 开发和雄辩的模型很陌生。我将使用存储库模式进行开发,在这种情况下,aboe 逻辑(产品+Sku 组合)位于何处。

Please help out.

请帮忙。

回答by Moppo

Yes, you can get the details of the products and skus without making one additional query per product using eager loading( this is referred as the typical N+1 query problemwhere N is the number of the products )

是的,您可以获取产品和 skus 的详细信息,而无需使用预先加载对每个产品进行额外查询 (这称为典型的N+1 查询问题,其中 N 是产品数量)

Suppose the relation between your Productand Skumodels model is:

假设您ProductSku模型模型之间的关系是:

Product

产品

public function skus()
{
    return hasMany('App/Sku','products_id');
}

To fetch the products data along with the sku data you can use the withmethod. In your controller:

要获取产品数据和 sku 数据,您可以使用该with方法。在您的控制器中:

Controller

控制器

 $products = Product::with('skus')->get();

Then, in your views, you can get the info this way:

然后,在您的视图中,您可以通过以下方式获取信息:

View

看法

foreach ($products as $product) 
{
     //$product->skus is a collection of Sku models
     dd( $product->skus );
}

For the repository question: if you want to use a repository you can place the eloquent-access part of your code inside the repository. So, for example you could have this method inside the repository:

对于存储库问题:如果您想使用存储库,您可以将代码的 eloquent-access 部分放在存储库中。因此,例如,您可以在存储库中使用此方法:

ProductRepository

产品库

public function getProductsData() 
{
    //access eloquent from the repository
    return Product::with('skus')->get();    
} 

then you can use your repository in your 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();
}

回答by Fester

If I understand your question correctly, you can use eager loading.

如果我正确理解您的问题,您可以使用预先加载。

 public function index()
 {
    $products = Product::with('skus')->get();
 }

This will give you an array of products that have a skus array in each product object.

这将为您提供一系列产品,每个产品对象中都有一个 skus 数组。

回答by Kaushik shrimali

If the repository pattern is used, do it like this.

如果使用存储库模式,请这样做。

public function index() {
    $data = $this->passportRepository->with('user')->findWhere(['id'=>1]);
}

回答by Vishrut_Naik

You can try this:

你可以试试这个:

public function index()
{
    $products = Product::all();
    foreach($products->skus as $product)
    {
         return $product;
    }

}

This will give you the exact result in the object form.

这将为您提供对象形式的确切结果。