Laravel 2 functions querybuilder - laravel

I would like to query multiple tables from multiple databases.
My first query should return an array of sites_id.
The second request should return manufacturers_id based on the sites_id returned in the first request.
How do I set this up?
My repository:
public function getSitesImminence()
{
$arraySites = PublicationSite::
select('sites_id')
->where('publi_code', '=', 'imminence_intercab')
->where('publi_status', '>', '0')
->get();
return $arraySites;
}
public function getManufacturersMls($arraySites){
$arrayManufacturers = Site::
select('manufacturers_list')
->where('sites_id', '=', $arraySites)
->get();
return $arrayManufacturers;
}
My controller:
$toto = $siteRepository->getSitesImminence()->getManufacturersMls($arraySites);
My error:
Method getManufacturersMls does not exist.

This isn't tested but your code should look more like this:
$arraySites = $siteRepository->getSitesImminence();
$toto = $siteRepository->getManufacturersMls($arraySites);
and your function should be a little different, using whereIn:
public function getManufacturersMls($arraySites){
$arrayManufacturers = Site::
select('manufacturers_list')
->whereIn('sites_id', $arraySites)
->get();
return $arrayManufacturers;
}

Related

Merging two queries does not return all available records

I'm having trouble merging two query results into an array - the merged output contains all the records of one of the queries ($factsheets) but only the last record of the other ($actives) where there are usually at least 3 records "available" to return.
My controller's code is as follows:
public function show($pest)
{
$theactives = self::getActives($pest);
$thefactsheets = self::getFactsheets($pest);
$merged = $theactives->merge($thefactsheets);
$result = $merged->all();
return $result;
}
public function getActives($pest){
$actives = Active::where('pests.id',$pest)
->join("active_pest","actives.id","=","active_pest.active_id")
->join("pests","pests.id","=","active_pest.pest_id")
->select('ai', 'groupcode', 'risk', 'pest')
->orderBy('ai')
->get();
return $actives;
}
public function getFactsheets($pest){
$factsheets = Factsheet::where('pest_id',$pest)
->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
->select('title', 'factsheets.id')
->orderBy('title')
->get();
return $factsheets;
}
Again, my expectation has exceeded my ability - what am I doing wrong here?
you can't merge objects of the result set. So, you have to convert your result into array first before the merge. Try the below script.
public function show($pest)
{
$theactives = self::getActives($pest);
$thefactsheets = self::getFactsheets($pest);
return array_merge($theactives, $thefactsheets);
}
public function getActives($pest){
return Active::where('pests.id',$pest)
->join("active_pest","actives.id","=","active_pest.active_id")
->join("pests","pests.id","=","active_pest.pest_id")
->select('ai', 'groupcode', 'risk', 'pest')
->orderBy('ai')
->get()->toArray();
}
public function getFactsheets($pest){
return Factsheet::where('pest_id',$pest)
->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
->select('title', 'factsheets.id')
->orderBy('title')
->get()->toArray();
}
You can use union in laravel
example
$silver = DB::table("product_silver")
->select("product_silver.name"
,"product_silver.price"
,"product_silver.quantity");
$gold = DB::table("product_gold")
->select("product_gold.name"
,"product_gold.price"
,"product_gold.quantity")
->union($silver)
->get();
then
dd($gold);

Joining 2 scopes laravel

I've been trying to solve this for quite a while now. I want to join these two scopes from my Match Model:
public function scopeMainMatches($query)
{
return $query->where('type', 'main');
}
public function scopeDotaMatches($query)
{
return $query->join('leagues', function ($join) {
$join->on('matches.league_id', '=', 'leagues.id')
->select('matches.*')
->where('leagues.type', '=', 'dota2')
->where('matches.type', '=', 'main');
});
}
so basically, when I put in into join eloquent relationship it will be the same like this:
$query = DB::table('matches')
->join('leagues', 'leagues.id', '=', 'matches.league_id')
->select('matches.*')
->where('leagues.type', '=', 'dota2')
->get();
it works fine during the terminal check. but I need to connect 2 scopes for the Controller which looks like this:
$_matches = \App\Match::mainMatches()
->get()
->load('teamA', 'teamB')
->sortByDesc('schedule');
so when I try to connect mainMatches and dotaMatches, it doesn't show up on the matches. although when i run php artisan tinker, it returns the correct output, but it won't show up on the matches table.
$_matches = \App\Match::mainMatches()
->dotaMatches()
->get()
->load('teamA', 'teamB')
->sortByDesc('schedule');
any Ideas how to work on this? TYIA!
I've managed to join two tables in just one scope here is the code:
public function scopeMainMatches($query) {
return $query->join('leagues','leagues.id','=','matches.league_id')->select('matches.*')->where('matches.type', 'main');
}

Laravel 5 - Use 'isAdmin' role check method when querying a model

I have implemented a basic role system that uses a table 'role_user'.
On my user model I have a few methods that check the roles, one of them is:
public function isStaff()
{
foreach ($this->roles()->get() as $role)
{
if ($role->id == 3)
{
return true;
}
}
return false;
}
How can I use this method when I am querying users?
This query here:
return User::where('name', 'like', "%".$request->name."%")
->orWhere('email', 'like', "%".$request->name."%")
->whereDoesntHave('Teams', function ($query) use($teamId) {
$query->whereId($teamId);
})
->with('teams')
->get();
Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)
You can using Scopes With Laravel instead of multiple methods to check for different methods.
public function scopeRole($query, $flag)
{
return $query->where('role', $flag);
}
and then
$users= User::role(3)->get();
check the reference tutorial for Creating Dynamic Scopes
it's better to do condition
return User::where('name', 'like', "%".$request->name."%")
->orWhere('email', 'like', "%".$request->name."%")
->whereDoesntHave('Teams', function ($query) use($teamId) {
$query->whereId($teamId);
})
->whereHas('roles', function($q) use ($role_id){
$q->where('id',$role_id);
})
->with('teams')
->get();
or also you can create a method for above query and based on param reurn result
You can have a scope called staff in your User model, then use that to narrow down your result:
public function scopeStaff($query, $roll_id = 3)
{
return $query->where('role_id', '=', $roll_id)
}
So when checking (with the model) for staff roles, you can improve the function that does that:
public function isStaff($role_id = 3)
{
return $this->role_id = $role_id ? $this : false;
}
Therefore, when using the query builder you can use the first method to narrow the result to those with the specified id, as you can see the default is 3 but will change to any value you give:
$staff_users = User::staff()->get();
Then the other one for verifying if a matched user model is a staff:
$user = User::find(1);
$is_staff = $user->isStaff(); //false or returns the same model
Hope this helps

laravel 5.2 if else to query database

stuck on a form that allows the user to enter a value into a choice of two fields. I can query the database using one field but want to add more range to database queries. With the following code below when i try to access the page to query it just shows me a white screen.
public function index()
{
$data = $request->all();
if(!empty($data['pstoreNum']))
{
$pstoreNum = $data['pstoreNum'];
$result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
}
else if(!empty($data['pweekNum']))
{
$pweekNum = $data['pweekNum'];
$result = DB::table('perfumes')->where('WeekNumber','=',$pweekNum)
->get();
return view('perfumes',compact('result'));
}
}
My routes file simple calls the index function. Any help would be appreciated.
You can add query functions within your query like so
public function index(Request $request)
{
$data = $request->all();
$result = \DB::table('perfumes')->where(function($query) use ($data) {
if(!empty($data['pstoreNum'])) {
$query->where('StoreNumber', '=', $data['pstoreNum']);
}
if(!empty($data['pweekNum'])) {
$query->where('WeekNumber', '=', $data['pweekNum']);
}
})->get();
return view('perfumes',compact('result'));
}
You can then use the one query and add multiple wheres on various conditions.
https://laravel.com/docs/5.2/queries#advanced-where-clauses

Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

I have the following relationship functions in my Job model:
public function resourceTypes(){
return $this->belongsToMany('ResourceType', 'job_requests');
}
public function resources(){
return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');
}
I am able to get an object with data from both of the above relationships using:
$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();
I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.
How would I do this?
Try something like this:
$job = Job::with('resources' => function($q) {
$q->with('resourceTypes')->where('flow_type',2);
})->findorfail($projectId);
In above you will get only those resources with flow_type = 2
I ended up using the following statement:
Job::with(['resources' => function ($query){
$query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
$result = DB::table('job')
->join('job_resources', 'job.id', '=', 'job_resources.job_id')
->join('job_requests', 'job_resources.request_id', '=', 'job_requests.id')
->where('job_resources.flow_type', '=', CONDITION)
->get();
Your table data is not clear from your input, but this method (query builder) should work

Resources