Laravel eloquent search both table in one to many relationship table - eloquent

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();

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 :)

how to select particular column from relationship collection table in laravel mongodb jessenger

I have 3 columns in my database. 2 columns is connected with one column by using a hybrid relationship.
here is my query.
$data=Client::with('product','department')->select(['product.product_name','product.product_description']);
how to select row from another table?
in your product or department relation method do the selection with all the forging keys if you have any other relation for product for later use is you want them like
public function product()
{
return $this->hasMany(department::class)->select(['id', 'another_relation_to_product_id', 'product_name', 'product_description']);
}
You can do it this way
$data = Client::with(['product:id,product_name,product_description','department'])->get();
see docs https://laravel.com/docs/5.7/eloquent-relationships#constraining-eager-loads in Eager Loading Specific Columns section. Or you can do it
App\User::with([
'product' => function ($query) {
$query->select('id', 'product_name', 'product_description');
},
'department'
])->get();

Laravel and Eloquent: Specifying columns in when retrieving related items

This is a followup post to: Laravel 4 and Eloquent: retrieving all records and all related records
The solution given works great:
$artists = Artist::with('instruments')->get();
return \View::make('artists')->withArtists($artists);
It also works with just:
$artists = Artist::get();
Now I'm trying to specify the exact columns to return for both tables. I've tried using select() in both the statement above and in my Class, like this:
ArtistController.php
$artists = Artist::select('firstname', 'lastname', 'instruments.name')->get();
or:
$artists = Artist::with(array('instruments' => function($query) {
$query->select('name');
}))->get();
(as suggested here and while this doesn't throw an error, it also doesn't limit the columns to only those specified)
or in Artist.php:
return $this->belongsToMany('App\Models\Instrument')->select(['name']);
How would I go about getting just the firstname and lastname column from the artists table and the name column from instruments table?
Not sure what I was thinking. I think working on this so long got me cross-eyed.
Anyhow, I looked into this a lot more and searched for answers and finally posted an issue on GitHub.
The bottom line is this is not possible as of Laravel v4.1.
https://github.com/laravel/laravel/issues/2679
This solved it:
Artists.php
public function instruments() {
return $this->hasMany('App\Models\Instrument', 'id');
}
Note that I changed this to a hasMany from a belongsToMany which makes more sense to me as a musicians (or Artist) would have many Instruments they play and an Instrument could belong to many Artists (which I also alluded to in my previous questions referenced above). I also had to specify 'id' column in my model which tells the ORM that instrument.id matches artist_instrument.id. That part confuses me a bit because I thought the order for hasMany was foreign_key, primary_key, but maybe I'm thinking about it backwards. If someone can explain that a bit more I'd appreciate it.
Anyhow, the second part of the solution...
In ArtistsController.php, I did this:
$artists = Artist::with(array(
'instruments' => function($q) {
$q->select('instruments.id', 'name');
})
)->get(array('id', 'firstname', 'lastname'));
That gives me exactly what I want which is a collection of Artists that contains only the firstname and lastname columns from the artists table and the name column for each of the instruments they play from the instruments.
$artists = Artist::with(array('instruments' => function ($query) {
$query->select('id', 'name');
}))->get('id', 'firstname', 'lastname');

How to use zend_db_select to update when there is two clause

I want to update an entry in the table when 2 conditions are met.
I have this statement, but it is only for one where condition
$this->dbo->update('mytable', $data, $this->dbo->quoteInto('id= ?', $id));
Instead of just checking where for just "id", i want to check for userid also..
Appreciate any help.
Something similar to this should work as the $where argument will accept and parse an array, reference the _whereExpr() method in Zend_Db_Adapter_Abstract for the code on how the $where arg is processed:
$this->dbo->update('mytable', $data, array('id= ?'=> $id, 'user_id=?'=>$userId));
I'm going to suggest that you may wish to alter you approach and use the save() method of Zend_Db_Table_Row instead of update. Here's an example.
public function saveUser($id, array $userData, $userId = null)
{
//$this->getDbAdapter is a placeholder for your choice of db adapters, I suggest a DbTable model that extends Zend_Db_Table_Abstract
$select = $this->getDbAdapter()->select();
//if userId is not null build a where clause
if (!is_null($userId)) {
$select->where('user_id = ?', $userId);
}
//build where clause for primary key, two where() in select() will be 'AND' use orWhere() for 'OR'
$select->where('id = ?', $id);
//fetch the row you wish to alter
$row = $this->getDbAdapter()->fetchRow($select);
//assign the data to the row, you can update any or all columns
$row->username = $userData[username];
$row->user_id = $userData[user_id];
//ect...
//save the new data to the row, will only update changed coluns
$row->save();
//return the whole for use in other ways, save() typically only returnbs the primary key.
return $row;
}
Yes this method is a little more verbose and maybe a touch more complicated. However as you start bumping up against the limits of 'INSERT' and 'UPDATE', save() can provide some useful functionality.

Using relationships to search in DBIx::Class

I am starting learning DBIx::Class and I have a doubt in searching in a related table:
Consider the following code:
my $books = $author->search_related('books', { name => 'Titanic' });
my $books = $author->books->search({name => 'Titanic'});
What I want is to only searches for books named 'Titanic' by the author in $author.
This two searches return the same resultset?
If yes, what is the best way and why?
If no, what is the difference?
search_related is a Resultset method. You'd use that if you had a resultset of Authors and you wanted to get a resultset of all of their books named 'Titanic'.
my $books = $schema->resultset('Author')->search({ last_name => 'Smith' })
->search_related('books', { name => 'Titanic' });
If $author is a row object, representing one row, then your second line is how you'd search his books.
my $books = $author->books->search({ name => 'Titanic' });
The distinction between rows and resultsets is one of the core concepts of DBIx::Class. You might want to review the DBIC Manual Intro. #dbix-class on irc.perl.org is usually pretty active so you can find help there as well.