I am working with laravel 8 and have the following table with their models structure
Orders
Id, store_id,client_id,delivery_date,created_at
order_details
Id,order_id,product_id,quantity,total_price
Products,
Id,product_name,product_image
users
id,name,phone,address
I want to retrieve data from 4 tables according to order id to display order with it's details as following json format for example
{
"id":1,
"delivery_date":"20-06-2021",
"created_at":"10-06-2021",
"order_details":[
{
"id":1,
"product_name":"TV",
"product_image":"http://xxxx.com/images/tv.jpg",
"quantity":1,
"total_price":3000
},
{
"id":1,
"product_name":"playstation",
"product_image":"http://xxxx.com/images/playstation.jpg",
"quantity":3,
"total_price":5000
}
],
"client":{
"id":1,
"name":"john",
"address":"somewhere"
}
}
but I don't know how to get these data write code using relations and eloquent in laravel
Some basic idea to help you.
Orders Model
public function products(){
$this->belongsToMany(Product::class,'order_details')->withPivot('quantity', 'total_price')->withTimestamps();;
}
public function client(){
return $this->belongsTo(User::class,'client_id','id');
}
So you can do some think like below to access it
Order::with(['products','client'])->find($orderId);
Similar question but on relationship insert
Ref:Attempt to read property "price" on null in laravel?
Related
I'm having trouble retrieving data through relationships.
My database structure (simplified):
orders:
id
user_id
product_id
order_items:
order_id
product_id
I need to get using relationships, all orders along with the items in the array.
Order model:
public function items()
{
return $this->hasMany(OrderItem::class, 'order_id', 'id');
}
Test controller:
public function test()
{
return Order::with('items')->get();
}
Result I got when accessing test():
[
{
"id": "d7baaae9-b925-4ff0-8bba-13e8e88d429b",
"user_id": "fa2a5f73-379d-4ab7-9bc5-81cdbd47f3b0",
"subtotal": "0.00",
"discount": "0.00",
"coupon_code": "0",
"total": "0.00",
"paid": false,
"refunded": false,
"created_at": "2022-07-26T16:41:50.000000Z",
"updated_at": "2022-07-26T17:51:45.000000Z",
"items": [
]
}
]
The "items" array does not exist in the orders table, it is coming through the relationship, but it comes empty. There is a record in the database relating orders with order_items, the OrderItem model is correctly accessing the database when I test. I don't know what the problem could be.
[EDIT_01]: I just found out that the problem is in the id I'm using, I'm using type Uuid (Ramsey\Uuid\Uuid\Uuid::uuid4()) for the keys of my tables, somehow it's not working, but when I testo with conventional ID works. Help-me.
I have the same issue, my fix is I add
protected $keyType = 'string';
to the table which has string id (uuid). Hope it can help
hope you found a solution, if not testing out your code sample here, and everything works fine for me,
public function items()
{
return $this->hasMany(OrderItem::class);
}
use this instead, should give you a better result
Try removing the third parameter and just use this:
return $this->hasMany(OrderItem::class, 'order_id');
This should work given your Database setup example, make sure you actually have items in your database that belong to that order you are debugging as well.
I want to display data in laravel.
This is the classrooms table:
This is the students table:
this is the classroom_student table :
I expect a result like this:
With class from the classroom table, year from the student table (the year the student was created), and data from the student table (data for each month, sample data:[2,4,6] means Jan: 2, Feb: 4, Mar: 6). I don't know how to make it. Can you help me? thank you
You need to setup a many to many relationship both of your models (classroom model and student model. It will look something like this:
class Classroom extends Model {
public function students(){
return $this->hasMany(Student:class, 'student_id');
}
}
class Student extends Model {
public function classrooms(){
return $this->hasMany(Classroom:class, 'classroom_id');
}
}
Here is also a reference to laravel docs for the exact solution:
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
You Should use HasMany Relation in both Models and while fetching data call this relation function to get data related to other model and set expected title for those data in Transformer.
I am using laravel VERSION = '5.6.22' . I have two tables t_project_employee and employees table
In t_project_employee i am storing the project_id and assigned employees.
eg pe_emp_id emp_id
01 25
01 36
02 25
In employee table i am storing employee details.
I am trying to fetch all employees who is assigned for a particular project.
public function employees(){
return $this->hasOne('App\Employee','emp_id','pe_emp_id')->select(array('emp_id', 'f_name','l_name'));
}
I am getting all projects and inside project i am getting employees. i need only employees details assigned to the projects. i done using the above code. how can i do this
return TProjectEmployees::where("pe_prj_id",$projectId)->with("employees")->get();
I am using above code in controller
[
{
"pe_id": 1,
"pe_prj_id": 1,
"pe_emp_id": 54,
"pe_role_id": 1,
"pe_startdate": "2018-07-11",
"pe_enddate": "2018-07-19",
"pe_IsActive": 1,
"employees": {
"emp_id": 54,
"f_name": "Aglubat Micheal",
"l_name": "Nicolas"
}
},
is the result. I dont need the project details, I only need the employees
As i show above example you have used hasOne relation as per my opinion use belongsTo relation because one project may be assign to multiple employee right? so your code will become like below:
public function employees() {
return $this->belongsTo('App\Employee','emp_id','pe_emp_id')->select(array('emp_id', 'f_name','l_name'));
}
You have a faulty relationship here. t_project_employees seems like an intermediate, or pivot, table for a many-to-many relationship. Therefore, you wouldn't have a model for that table or ever query that table directly. You'd have a belongsToMany relationship on both the Projects and Employees Model.
Employee Model:
public function projects()
{
return $this->belongsToMany(Project::class, 't_project_employees');
}
Then query that relation: https://laravel.com/docs/5.6/eloquent-relationships#querying-relations.
Employee::whereHas('projects', function($q) use ($projectId) {
$q->where('id', $projectId);
});
I'm having the following problem, I'm using scope in Laravel and I have the following relationship:
Enquiry
pickup_address
dropoff_address
Notes
This is referenced in the model:
public function pickup_address() {
return $this->belongsTo('App\Address', 'pickup_address', 'id');
}
I want to return the enquiry, as well as postcode which is stored in the Address table. I just want this column from this table and I have done the following:
return $query->with(['pickup_address' => function ($query) {
$query->select('postcode');
}])->get();
This gives the following (json):
{
"id":1,
"pickup_address":null
"notes":"hello world",
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
This is not giving the postcode and just gives the pickup_address as null. However, removing the $query->select('postcode') gives:
{
"id":1,
"pickup_address": {
"id":140,
"house_number":null,
"address_1":"Address 1",
"address_2":null,
"postcode":"POSTCODE",
"city":"CITY",
"county":"C0UNTY",
"created_at":"2017-06-08 09:56:23",
"updated_at":"2017-06 0}",
"notes":"Hello world","
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
However, I'm using Vue and using a table, so I just need the particular field to be returned that matches the column, rather than the entire object being returned.
Can anyone suggest a solution, please? I have followed some examples online and they suggest the $query->select('postcode')
how can i merge laravel relationship results in to one object?
MyController.php
public function getUser($id) {
return TournamentUser::where('customer_id','=', $id)->with('user')->get();
}
MyModel.php
public function user() {
return $this->hasOne('App\Models\Customer','customer_id', 'customer_id');
}
returning result :
[{
"id":1,
"tournament_id":3,
"customer_id":2016827550,
"point":0,
"user":{
"id":1,
"customer_id":2016827550,
"nickname":"OMahoooo"
}
}]
as expected query returns user section as array but i expect result like this :
[{
"id":1,
"tournament_id":3,
"customer_id":2016827550,
"point":0,
"nickname":"OMahoooo"
}]
only get nickname section without user array. I hope you understand me.
Sorry for my english , have a nice day
You can load the data and remap it manually using map() method. I've just tested this code and it works perfectly with hasOne() relationship:
$users = TournamentUser::where('customer_id', $id)->with('user')->get();
$users->map(function ($i) {
$i->nickname = $i->user->nickname; // Set related nickname.
unset($i->user); // Delete user data from the collection.
return $i;
});
Alternatively, you could use an accessor, but in this case, you'll meet the N+1 problem.