Eloquent using parent field in subquery - eloquent

How can i access the 'id' field in the first query, and use it in the second subquery in this example:
$users = \App\User::where('active', 1)->where('deleted_at', null)->where('recieve_jobagent', 1)
->with(['companies' => function($query){
$query->where('active', 1);
$query->with(['posts' => function($posts){
$posts->where('active', 1);
$posts->whereHas('users', function($postUsers){
**I do not have access to 'users.id' here**
$postUsers->where('user_id', 'users.id');
});
}]);
}]);
I'm using lumen 5.1.
My goal here is to get all users and their related companies, and the companies' posts that isn't related to the user.

I dont think you need to do that. You can use whereHas and by drilling down into the relationships it returns only the ones that belong to the thing you're querying.
Without seeing your relationship structure, I would assume you need something like this?
$users = \App\User::where('active', 1)->where('deleted_at', null)->where('recieve_jobagent', 1)
->whereHas('companies', function($query){
$query->where('active', 1)
->whereHas('posts', function($query){
where('active', 1);
})
})
->with(['companies' => function($query){
$query->where('active', 1);
$query->with(['posts' => function($posts){
$posts->where('active', 1);
}]);
}]);

Related

Eloquent select items with several where clause on same relationship column

I have a User model with a hasMany relations to model Cart.
Cart model has (among others) user_id and campaign_id.
I want to make a request which will grab all the users who have a cart with a specific campaign_id and also at least one of a list of campaign ids.
I came up with this request
$alistUsers = User::whereHas('cart', function($query) use($campaignId, $campaignIds){
$query->whereIn('campaign_id', $campaignIds)
->where('campaign_id', '=', $campaignId)
;
})
->get()
;
which obviously returns 0 results since a cart item can't have several campaign_id.
I probably need to do something with sub selects but I can't find the correct answer.
If someone has an idea I'm all ears.
Thanks.
I finally ended up with 2 different queries
$userIds = User::whereHas('cart', function($query) use($campaignId, $campaignIds){
$query->where('campaign_id', '=', $campaignId);
})
->pluck('uuid')
->toArray()
;
$iKnowUsers = User::whereHas('cart', function($query) use($userIds, $campaignIds){
$query->whereIn('campaign_id', $campaignIds)
->whereIn('user_id', $userIds );
})
->get()
->count();
But I'm not really happy with that so if someone has a cleaner answer I'll be interested to see it :)

Laravel eloquent search both table in one to many relationship table

My two table Member and Deposit there has one to many relationship one member has multiple deposit in Deposit table i want to search by multiple column both table which will have to match.
This is my Member Table
1.id,
2.branch_id,
3.village_id,
4.user_id,
5.name,
6.phone,
7.email,
8........
My Deposit Table
1.meber_id,
2.user_id
3.deposit_date,
4.deposit_amount,
5.total_amount,
6..........
My Controller Code
$depo = Deposit::with(['member'=>function($query){$query->where('branch_id',$request->branch_id)->where('status','running')->get();}])->where('user_id',$request->user_id)->whereDate('deposit-date','>=',$from_date)->whereDate('deposit-date','<=',$to_date)->get();
if i do that then ....$query->where('branch_id',$request->branch_id)->get()..... section is not working please help me any one
Try this:
$depo = Deposit::whereHas('member', function($query) use ($request){
$query->where([
['branch_id' => $request->branch_id],
['status'=> 'running']
])
})
->where('user_id',$request->user_id)
->whereDate([
['deposit-date','>=',$from_date],
['deposit-date','<=',$to_date]
])->get();
Your question is quite ambiguous, but looks like you need to use the $request in the with function.
$deposits = Deposit::with(['member' => function ($query) use ($request) {
$query->where('branch_id', $request->branch_id)
->where('status', 'running')->get();
}])->where('user_id', $request->user_id)
->whereDate('deposit-date', '>=', $from_date)
->whereDate('deposit-date', '<=', $to_date)
->get();
But the with method wont filter down your query it will simply limit the number of members returned with all the deposits. It's not searching in the member table.
UPDATE 04/12/2018
Without checking the docs at all, and completely off the top of my head.
Deposit::with('member', function($query) use($request){
$query->where('branch_id', $request->branch_id)
->orWhere('village_id', $request->village_id)
})->where(function($query) use($request) {
$query->where('user_id', $request->user_id)
->whereDate('deposit-date', '>=', $from_date)
->whereDate('deposit-date', '<=', $to_date)
})->orWhereHas('member', function($query) use($request){
$query->where('branch_id', $request->branch_id)
->orWhere('village_id', $request->village_id)
})->get();

Laravel 5.1 - Querying multiple relationships

I've got a problem which I don't know how to solve.
I've got companies which have a profile(profile belongs to company) and have locations(company has many locations).
I'm trying to get all companies which have a name like $request->input('search_term') and have a least one location with a zip or city matching $request->input('search_addition') and a profile with a type of 0.
My code is:
$companies = Company::with(['profile' => function ($query) {
$query->where('type', 0);
}])
->whereHas('locations', function ($query) use ($request) {
$query->where('zip', 'like', '%'.$request->input('search_addition').'%')
->orWhere('city', 'like', '%'.$request->input('search_addition').'%');
})
->where('name', 'like', '%'.$request->input('search_term').'%');
At the end I add $companies = $companies->paginate(25);
The result I get is not what I want. I get all companies which have a name like $request->input('search_term'). It ignores the type of the profile and the locations. The locations array is empty for those companies which don't match the specified search_addition but it still returns the company.
with() is used for relationship eager loading either with or without constraint, not used as a constraint to filter the parent model which you need to use where function family instead.
This is what I think the code should be (not tested).
$companies = Company::with('profile')
->with(['locations' => function ($query) use ($request) {
$query->where('zip', 'like', '%'.$request->input('search_addition').'%')
->orWhere('city', 'like', '%'.$request->input('search_addition').'%');
}])
->whereHas('profile', function ($query) {
$query->where('type', 0);
})
->whereHas('locations', function ($query) use ($request) {
$query->where('zip', 'like', '%'.$request->input('search_addition').'%')
->orWhere('city', 'like', '%'.$request->input('search_addition').'%');
})
->where('name', 'like', '%'.$request->input('search_term').'%');

Perl Catalyst: Resultset and Relations

I have two tables in my database and one of the tables is associated with my Accounts table.
So in my Schema Result for Account.pm I added the following line.
__PACKAGE__->has_many('subjects', 'MyApp::DBIC::Schema::Subject', {'foreight.account_id' => 'self.account_id'});
Then in my controller I make a search like this.
$c->stash->{search_results} = $c->model('DB::Account')->search(
{ -or => [
firstname => {like => '%'.$search_term.'%'},
'subjects.subject_title' => {like => '%'.$search_term.'%'},
]
},
{
join => 'subjects',
rows => '3',
},
{
order_by => 'first name ASC',
page => 1,
rows => 10,
}
);
It does not output any errors, but I can't figure out how to output the results on my view file. Is this a correct method of making relations between two tables?
My goal: provided a search_term, search two tables and output the result in view file. My SQL would look something like this:
SELECT FROM Accounts,Subjects WHERE Accounts.firstname=$search_term OR Subjects.subject_title=$search_term LEFT JOIN Subjects ON Accounts.account_id=Subject.account_id
And would want to output the result in view file, as I stated above.
I am fairly new to Perl and some of the documentations don't make that much sense to me, still. So any help and tips are appreciated.
The join looks OK to me, but it would make sense to try a simplified version without the join to check that everything else is OK.
The behaviour of DBIx::Class::ResultSet::search differs depending on the context in which it's called. If it's called in list context then it executes the database query and returns an array of MyApp::DBIC::Schema::Account objects. For example:
my #accounts = $c->model('DB::Account')->search();
In your case you're calling search in scalar context, which means that rather than returning an array it will return a DBIx::Class::ResultSet object (or a subclass thereof), and crucially it won't actually execute a db query. For that to happen you need to call the all method on your resultset. So, assuming you're using the default template toolkit view you probably want something like this:
[% FOREACH search_result IN search_results.all %]
[% search_result.first_name %]
[% END %]
This 'lazy' behaviour of DBIx::Class is actually very useful, and in my opinion somewhat undersold in the documentation. It means you can keep a resultset in a variable and keep executing different search calls on it without actually hitting the DB, it can allow much nicer code in cases where you want to conditionally build up a complex query. See the DBIx::Class::Resultset documentation for further details.
You have error in your query:
Try:
$c->stash->{search_results} = $c->model('DB::Account')->search(
{ -or => [
firstname => {like => '%'.$search_term.'%'},
'subjects.subject_title' => {like => '%'.$search_term.'%'},
]
},
{
join => 'subjects',
order_by => 'firstname ASC',
page => 1,
rows => 10,
}
);

Is it possible to use sort() on multiple fields in Doctrine 2 ODM?

I am doing a query on a result document in my doctrine mongodb *odm*. There are two indexed fields in the document which I would like to use in sort. I have written something like:
$results = $this->createQueryBuilder('Document\Score')
->sort('finalScore', 'desc')
->sort('date', 'desc')
->getQuery()
->execute();
Here the second sort() function overrides the first one and the designated result is never found.
Thanks in advance for the nice help.
Try this
$qb = $this->createQueryBuilder('Document\Score');
$qb->sort(array(
'finalScore' => 'desc',
'date' => 'desc',
));
$results = $qb->getQuery()->execute();