I have three tables:
users
id
name
role_id
password
...
role_user
id
role_id
user_id
roles
id
name
slug
...
Now I want to get a user list with users.id,users.name,
roles.id. That's my code:
$query = User::with(['roles'=>function($q){
$q->lists('role_id');
}])->get(['id','name']);
the response like that
{
"id": "1",
"name": "aaaa",
"roles": []
},
{
"id": "2",
"name": "bbbb",
"roles": []
},
when i don't pass the array to get method,the response like that:
{
"id": 1,
"name": "aaaa",
"password": "xxxxxxx",
"created_at": "2015-05-07 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 1,
"role_id": 2
}
}
]
},
{
"id": 2,
"name": "bbbb",
"password": "xxxxxxx",
"created_at": "2015-05-05 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 2,
"role_id": 2
}
}
]
},
But i do not want the password,created_at and pivot field. How to filter these?
To get relations you need to get the foreign keys. Try this
$query = User::with(['roles'=>function($q){
$q->get(['id', 'name', 'slug']);
}])->get(['id','name', 'role_id']);
As for the pivot table, can you post you roles relation in the user model?
Edit
Add this to your user model to hide the pivot properties
protected $hidden = ['pivot'];
You can add more fields to that property to remove them from all queries.
Related
I want to pull the invoice detail with the "id" number of 3 in the tools table from the "invoice_details" table. "plate" "invoice_details" relationship "plate_no" in the "trucks" table, but when I pull the data, a different data is coming, where am I making a mistake?
public function getTruck($id)
{
$truck = Truck::find($id)->with(['truckHistory'])->first();
return $truck;
}
Truck extends Model
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
}
Normally the incoming data is TRUE when I don't write a with condition
THIS IS TRUE
$truck = Truck::find(3);
{
"id": 3,
"plate": "73AD323",
"created_at": "2021-10-13T08:38:23.000000Z",
"updated_at": "2021-10-13T08:38:23.000000Z"
}
When I type a condition, the id is wrong.
$truck = Truck::find(3)->with(['truckHistory'])->first();
{
"id": 1,
"plate": "33EER36",
"created_at": "2021-10-11T06:01:29.000000Z",
"updated_at": "2021-10-11T06:01:29.000000Z",
"truck_history": [
{
"id": 1,
"plate_no": "33EER36",
"created_at": "2021-10-11T06:03:16.000000Z",
"updated_at": "2021-10-11T06:03:16.000000Z"
},
{
"id": 2,
"plate_no": "33EER36",
"created_at": "2021-10-11T06:06:18.000000Z",
"updated_at": "2021-10-11T06:06:18.000000Z"
}
]
}
Using first will return the first record of the trucks table, to do so you can use
Truck::with(['truckHistory'])->find($id);
I want to filter users based on their subscription_status which s stored in a pivot table.
I have Three tables users , subscription_packages , subscription_package_user
$user=User::with(['studentDetails','subscriptionsSatus.courses'])
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
this code return the response is
[
{
"id": 44,
"first_name": "Abcd Test",
"last_name": "Test lastname",
"student_details": null,
"subscriptions_satus": [
{
"id": 1,
"name": "Gold",
"price": 3000,
"user_id": "2"
"pivot": {
"user_id": 44,
"subscription_package_id": 1,
"subscription_status": "on_free_trial",
"expires_on": null,
"id": 9
},
"courses": [
{
"id": 18,
"title": "English Grammar for Class 3",
"price": 400,
"strikethrough_price": null,
"status": "draft",
"user_id": 2,
"image": "http://127.0.0.1:8000/courses/1615702915.png",
"description": null,
"pivot": {
"subscription_package_id": 1,
"course_id": 18,
}
}
]
}
]
}]
i want to return only users who having subscription_status =$filter.
$filter='acive'or 'on_free_trail'
my model is
public function subscriptionsSatus()
{
return $this->belongsToMany(SubscriptionPackage::class)->withTimestamps()->withPivot('subscription_status','expires_on','id');
}
I havetried
$filter=$request->input('filter')??"active";
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
But Got error Column not found 'pivot'
You need to use wherePivot along with the orWhere like below:
public function subscriptionsStatus()
{
return $this->belongsToMany(SubscriptionPackage::class)
->withTimestamps()
->withPivot('subscription_status','expires_on','id')
->wherePivot(function($q){
return $q->where('subscription_status','=','active')
->orWhere('subscription_status','=','on_free_trail');
});
}
Update
Or in your controller:
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->withPivot('subscription_status')
->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
There two models user and also address, which contains country, city and etc. I need to get a list of users with the city, not with the whole address. Relation is oneToOne. The only thing I can get, using select['user_id', 'city']:
{
"id": 1,
"name": "John",
"city": {
"user_id": 3,
"city": "Paris"
},
but I need:
{
"id": 1,
"name": "John",
"city": "Paris"
}
Of course, I can use a loop and do something like $user->city = $user->address->city but maybe there is a better way to solve this problem. Laravel 5.4
You can use Accessor,
And append the attribute to json appending-values-to-json:
In your User model:
protected $appends = ['city'];
public function getCityAttribute()
{
return $this->city->city;
}
Test it like this:
User::with('city')->get()->toJson();
// It will return:
// [{"id": 1, "name": "John", "city": "Paris", "city" : {"user_id": 3, "city": "Paris"}}, {...}]
I have a table user_childrens whose contains id_parent and id_user.
I'm trying to list all childrens of the parent with this:
code:
//relation in model via belongsTo
$idparent = auth('api')->user()->id;
$list = UserChildren::where('id_parent',$idparent)
->with('child:id,name,email')
->get();
return $list->toJson();
The return is:
[
{
"id": 1,
"id_parent": 1,
"id_user": 1,
"created_at": null,
"updated_at": null,
"child": {
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel#example.com"
}
},
{
"id": 4,
"id_parent": 1,
"id_user": 2,
"created_at": null,
"updated_at": null,
"child": {
"id": 2,
"name": "Krystel Lehner",
"email": "cernser#example.net"
}
}
]
But it's API so I want only the child column like:
[
{
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel#example.com"
},
{..}
]
UserChildren Model:
public function child() {
return $this->belongsTo('App\User','id_user','id');
}
I know that I could do this via .map() on collection but maybe there is other solution already on this query
You can use this code
$idparent = auth('api')->user()->id;
$childs = User::whereHas('user_childrens', function ($query) use ($idparent) {
$query->where('id_parent', $idparent);
})->get(['id', 'name', 'email']);
dd($childs->toJson());
And User model define user_childrens relation.
public function user_childrens()
{
return $this->hasMany('App\UserChildren','id_user','id');
}
See also docs https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence
The platform has a many to many relationship, where the table assigned_users holds all Users assigned to CalendarEvents.
I need to fetch, through CalendarEvents, the assigned users as an object, showing each user's information. So, I want to access the User through AssignedUsers, because I wanna fetch all the users related to that event.
public function assignedUsers()
{
return $this->hasManyThrough(Users::class, AssignedUsers::class, 'user_id', 'id');
}
It works, but it shows only the first user in the table. I want to show all of them. Currently there are 3.
"assigned_users": [
{ id: 1, ... }
]
If I do the following:
public function assignedUsers()
{
return $this->belongsToMany(Users::class, "assigned_users", "event_id", "event_id");
}
It will fetch 3 results, but all the information will be from the same user. It will repeat the same user 3 times. Changing both the event_id to user_id and id, and id and user_id will have the same result.
"assigned_users": [
{ id: 1, ... },
{ id: 1, ... },
{ id: 1, ... },
...
]
What I am trying to accomplish is the following result:
{
"status": "200",
"success": true,
"data": [
{
"event_id": 1,
"event_key": "EB1M7OGJRPW0",
"calendar_id": 4,
"start_at": "2018-01-01 00:00:00",
"end_at": "2018-01-31 00:00:00",
"location": "123 Lorem, Ipsum",
"event_name": "Event #1",
"description": "Lorem ipsum dolor sit amet",
"added_at": "2018-02-07 09:07:31",
"created_by": {
"id": 4,
"name": "Foo Bar",
"email": "foobar92#gmail.com",
"first_name": "Foo",
"last_name": "Bar",
"status": "active",
"is_activated": 0,
"created_at": "2018-02-07 09:06:49",
"updated_at": "2018-02-07 09:06:49"
},
"assigned_users": [
{
"id": 1,
...
},
{
"id": 2,
...
},
{
"id": 3,
...
},
...
]
}
]
}
This is not the case of hasManyThrough relationship. Here assigned_users is a pivot table so you just need a belongsToMany relationship defined
public function assignedUsers()
{
return $this->belongsToMany(Users::class, 'assigned_users', 'event_id', 'user_id');
}
and for this to work, you may have to change the calendar_events table's primary key to id (instead of event_id)