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?
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.
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".
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With