Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only relations from eloquent query

I got the following code:

$popularProducts = PopularProduct::with('product')->get();

This is how I get all of products from popular_products (contains only product_id) table with relations for products table. But I have this result:

Collection {#409 ▼
  #items: array:1 [▼
    0 => PopularProduct {#411 ▼
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:4 [▶]
      #original: array:4 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "product" => Product {#462 ▶}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
}

I need to take only relations->product field. How can I take it?

like image 371
Alexxosipov Avatar asked Feb 27 '18 09:02

Alexxosipov


People also ask

Is query Builder faster than eloquent?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What is hasOne in Laravel?

Laravel, one of the most popular PHP frameworks, has several functions, like user online or offline on Laravel, that make it attractive for developers, one of them being hasOne, which basically allows communication or relationship between two tables. Its name means "create a one-to-one relationship".


1 Answers

You can do it like this

$products = PopularProduct::with('product')->get()->pluck('product');

if you like the result to be keyed you can do it like this

$products = PopularProduct::with('product')->get()->pluck('product','id');

// you can key it with **id** of the table (popularProduct) or by **id_product** of relationship (product)

if you like only to retrieve specific fields from relation you can try something like this

 $products = PopularProduct::with('product:id,product_name')->get()->pluck('product','id');
like image 51
aitbella Avatar answered Sep 20 '22 22:09

aitbella