Can I select value from relationships with function "with" ?
So make something like this:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
Yes I know that I can put select in relation "user_detail" but can I select in with function?
You can select within with as you made the example given below:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
But it won't not work (as you commented in other answer) because you've only selected a single property but the foreign key is not available in your select statement. So, make sure that, you also select the related foreign key as well and then it'll work.
In your case, I believe that, you've to also select the user_id in your select for example:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select(
'user_id', // This is required if this key is the foreign key
'detail_1'
);
}])->get();
So, without the foreign key that makes the relation, Eloquent won't be able to load the related models and that's why you get null in your result as you mentioned in other comment.
Yes, you can use select() inside with(). Just pass an array of columns:
$query->select(['detail_1', 'detail_2']);
Alternatively, you can create another relation and add select() to it:
public function userDatails()
{
return $this->hasMany('App\UserDetail')->select(['detail_1', 'detail_2']);
}
$result = Staff::where('live_status',2)
->with('position')->with('department')->with('gender')
->with(['partner' => function($query){
$query->where('alive',0);
}]);
Related
So I have a many-to-many table with created_at and the foreign keys student_id and status_id.
For each student, I want to retrieve an entry only if the latest one has status_id = 1.
I tried it like this: (it's a chain of queries, in this case $query would be Student::where(something else))
$query->whereHas('statusuri', function($query) use ($statusuri) {
$query->latest('status_student.created_at')->where('status_id', 1);
});
(statusuri is the many-to-many relationship)
but I get a different result from what I need.
It does the where clause first and then latest(). Basically, it retrieves the last entry which matches the where.
I want to search for each student, the latest entry and if the where clause matches it, get that entry. If not, don't return anything.
Is that possible with Eloquent?
Thanks.
In your case, you can use the where and latest methods together in a subquery, like this:
$query->whereHas('statusuri', function($query) use ($statusuri) {
$query->where(function($query) {
$query->where('status_id', 1)
->latest('status_student.created_at');
});
});
Have you considered a "has one of many" relationship : https://laravel.com/docs/9.x/eloquent-relationships#advanced-has-one-of-many-relationships
You can make a relationship in your Student model:
public function latestStatus()
{
return $this->hasOne(StatusStudent::class)->ofMany([
'created_at' => 'max',
'id' => 'max',
], function ($query) {
$query->where('status_id', 1);
});
}
Edit: works only for Laravel 8+
How can achieve this query?
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('catalog.price')]);
This is not working, it shows undefined table... I tried to put the name of the table but it's the same.
On the internet I always found the easy query:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => 5]);
Okay! When I want to update all rows with the same value is easy, in addition is easy when you want to update with a column of the same table like:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('price_alternative')]);
But how about using a column of another table with a relationship? I haven't found the solution.
I know this can be solved using entire raw query, but I wanted to know if it can be achieved by the eloquent way
You probably need to join in the catalog table on your querybuilder. This is different than using with(). Something along the lines of
Sale::whereIn('id', $ids)
->join('catalog', 'sales.catalog_id', '=', 'catalog.id')
->update(['price' => DB::raw('catalog.price')]);
This is not better than answer of #Qirel, but it is Eloquent way, i like this because that's more clearly.
$Sales = Sale::whereIn('sales.id', $ids)
->with('Cat')->get();
$Sales->map(function($q){
$q->price = $q->Cat->price;
$q->save();
});
Assume you have this relation code in Sale model:
public function Cat()
{
return $this->hasOne(CatModel::class, 'id', 'catalog_id');
}
How to pass _user_id column value inside with in $query. this is hasMany relationship. I am not able to figure out how to user user_id of RFX into the $query where condition.
public function response_pricings(){
return $this->hasMany('App\Models\Website\RFXRequestPricingResponse', ['rfx_request_id'=>'_rfx_request_id', 'user_id'=>'_user_id'])->selectRaw("*");
}
return RFXRequestSupplierResponded::select(
'id as _id',
'rfx_request_id as _rfx_request_id',
'user_id as _user_id',
'status',
'is_qualified',
DB::RAW('(SELECT name FROM users WHERE id=user_id) as user_name'),
DB::RAW('(SELECT note FROM rfx_request_response_notes WHERE rfx_request_id='.$rfx_request_id.' AND user_id=rfx_request_suppliers_responded.user_id LIMIT 1) as note')
)
->with(
[
'response_pricings' => function ($query) {
/*$query->where('user_id', $_user_id);*/
}
]
)
->where('rfx_request_id',$rfx_request_id)
->get();
When you have defined a relationship on a model, Laravel would automatically link the models using either the dynamically determined foreign keys or foreign keys that you have specified. Therefore you don't need to pass in the user_id to the query. Laravel would automatically use the the user_id of the RFXRequestSupplierResponded instance.
However, it looks like you are linking the RFXRequestSupplierResponded to the RFXRequestPricingResponse model using multiple foreign keys. Eloquent doesn't have built-in support for that. Take a look at the answers to this question for examples on how to add support for multiple foreign keys.
You pass local scope parameters to closure functions using use
... ->with(
['response_pricings' => function ($query) use ($_user_id) {
$query->where('user_id', $_user_id);
}
]
)
->where(....
More info in this Q&A: In PHP 5.3.0, what is the function "use" identifier?
Hello i have a CommentRetours table which connects the retours to the comments.
The DB:
I need to display all comments for a user and return that to the view.
I now have this query:
$comments = CommentRetours::with(['comments' => function($q) {
$q->where('user_id',Auth()->user()->id);
}])->get();
This return NULL..
The user_id is inside the comments table.
As constructure example i will add this:
What am i doing wrong?
The question is quite old but the solution adopted by OP being less than ideal, here is what he probably should have done:
$comments = CommentRetours::whereHas(['comments' => function($q) {
$q->where('user_id', Auth::id());
}])->with('comments')->get();
whereHas checks if the CommentRetours have some comments that match the condition.
I also replaced Auth()->user()->id by Auth::id().
I fixed it by adding user_id to the CommentRetours table, now I wont have to query inside the other relationship.
I can just see user_id directly inside the table.
Currently i am doing this to get branch table data:
$smlist = SM::where('branch_id','=',$branchid)->select('id','name','branch_id')->get();
foreach ($smlist as $sm) {
$sm->b = SM::find($sm->id)->branch;
}
Where branch_id is foreign key, also I set belongsTo in SM table.
This is working fine for me but I am finding way to use it with in single query.
How can i get this data using single query?
You can eager load your relationship using with():
$smlist = SM::with('branch')
->where('branch_id','=',$branchid)
->select('id','name','branch_id')
->get();
You have to use a join, here you can find the documentation http://laravel.com/docs/4.2/queries#joins
I think you can use something like this:
SM::->join('branch', 'branch.id', '=', 'sm.branch_id')
.where('sm.branch_id','=',$branchid)
->select('sm.id','sm.name','sm.branch_id','branch.name')
->get();