I have two models EcommerceOrders and Medicines
class EcommerceOrders extends Model
{
use HasFactory;
protected $table = 'ecommerce_orders';
protected $fillable = [
'user_id',
'manager_id',
'first_name',
'last_name',
'phone_number',
'email',
'address',
'city',
'zip_code',
'other_info',
'products',
'total_price',
'qr_code',
'status',
'assigned_to',
'save_client_info',
];
class Medicines extends Model
{
use HasFactory;
use Notifiable;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $table = 'medicines';
protected $fillable = [
'name',
'subcategory_id',
'group',
'unity',
'description',
'price',
'discount',
'type',
'photo_path',
'slug'
];
In the EcommerceOrders Model the products field holds info about the items purchased by a client What I'm trying to do is to get the data about those products.This is how i have created the relationships in each model
EcommerceOrders
public function items()
{
return $this->hasMany(Medicines::class,'id');
}
Medicines
public function ecomOrders()
{
return $this->belongsTo(EcommerceOrders::class);
}
However when i try to get the data It only displays the information about the first item in products
EcommerceOrders::where('id',3)->with('items')->get()
Illuminate\Database\Eloquent\Collection {#3313
all: [
App\Models\EcommerceOrders {#3298
id: 3,
user_id: 2,
manager_id: 3,
first_name: "test",
last_name: "test1",
phone_number: "3550123456",
email: "[email protected]",
address: "addsss",
city: "qwerr",
zip_code: "625",
other_info: null,
products: "{"2":1,"3":1}", //id: quantity
total_price: "8309,00",
qr_code: "2416718593exKrLbcNEpVm3nYI6S31652402",
status: "ordered",
assigned_to: null,
save_client_info: 1,
created_at: "2022-11-22 17:35:32",
updated_at: "2022-11-22 17:35:32",
items: Illuminate\Database\Eloquent\Collection {#3315
all: [
App\Models\Medicines {#3327
id: 3,
group: 11,
name: "quisquam",
subcategory_id: 8,
unity: "499mg",
description: "Quo autem aut quibusdam dolorem aut sit.",
price: 6935.0,
discount: 9.0,
type: 0,
photo_path: "https://via.placeholder.com/640x480.png/009900?text=laudantium",
slug: "quisquam",
created_at: "2022-11-21 11:39:29",
updated_at: "2022-11-21 11:39:29",
deleted_at: null,
},
],
},
},
],
}
CodePudding user response:
EcommerceOrders::where('id',3)->with('items')->get()
this query only gets the row where the id is 3 and since it is and increment ID, only 1 item will be ID:3
CodePudding user response:
//this is how you can retrieve hasMany data
$items = EcommerceOrders::find(1)->items;
foreach($items as $item){ //
}
CodePudding user response:
//this is how you can retrieve hasMany data in different tables.
$items = EcommerceOrders::find(auth->user())->items;
foreach($items as $item) {
//
}