Laravel fetch data from two tables without join with pagination - php

I want to fetch results from two tables properties and properties_x where properties.address or properties_x.address_x like test with laravel pagination.
There is no foreign key relationship between these two tables.
properties
id name address
1 test1
2 test2
3 test3
4 test3 test
5 test4 test
properties_x
id name address
1 test1_x test
2 test2_x
3 test3_x
4 test3_x test
5 test4_x
Expected results:
name address
test3 test
test4 test
test1_x test
test3_x test

Use union all to union two table's datas,
And get the columns from these datas in DB, so you can use pagination.
try it like this:
$p1 = DB::table('properties')
->where('address', 'test')
->select('name', 'address');
$p2 = DB::table('properties_x')
->where('address', 'test')
->select('name', 'address');
$p = $p1->unionAll($p2);
DB::table(DB::raw("({$p->toSql()}) AS p"))
->mergeBindings($p)
->select('name', 'address')
->paginate(10);

I don't know if there is another way, but it works for me well
$res= [];
$tableONe = Property::where('address','test')->get();
array_push($res,$tableOne);
$tableTwo = PropertyX::where('address','test')->get();
array_push($res,$tableTwo);
now $res have both data table together

union all then laravel query builder provide unionAll method for mysql union. when you are doing big project or ERP level project then mostly you require to use union for getting data from database with multiple table. In Following example you can see how to use union all in Laravel 5.
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")
->unionAll($silver)
->get();
print_r($gold);

$users = User::select('id','name')
->where('name','LIKE','%'.$key.'%');
$properties = Property::select('id','name')
->where('name','LIKE','%'.$key.'%');
$results = Program::select('id','name')
->where('name','LIKE','%'.$key.'%') ->union($users)
->union($properties)
->simplePaginate();

Related

fetch and push the data in new table

I have the table 'project','user' and 'role_mapping'.I want to to fetch the project_owner_id from the project table and push the user_id which is fetched from user table and role_id=1 in role_mapping table.one project owner has multiple project.so I want to restrict duplicate entry. I want to do it in laravel controller controller.
project table
project_id project name project_owner_id
1 DEC01
2 DEC02
3 DEC01
user table
id user_string
1 DEC03
2 DEC01
3 DEC02
role_mapping table
user_id role_id
2 1
3 1
$heads = DB::table('project')
->join('users', 'project.project_owner_id', '=', 'users.user_string')
->select('project.project_owner_id','users.id as user_id')->get();
foreach($heads as $head){
print_r($head->project_owner_id);
print_r($head->user_id);
}
The below query fetched project owner id and user_id.How to push the value in role_mapping table
Try to refer to this one, using Attach, Detach in laravel : http://kaloraat.com/questions/laravel-attach-detach-and-sync-methods
Hope this helps :)
Like this way
Assuming your model name as MappingTable
foreach($heads as $head){
$mapTable = new MappingTable();
$mapTable->user_id = $head->user_id;
$mapTable->role_id = $head->project_owner_id;
$mapTable->save();
}
OR alternatively you can pass $data array like this
$data = array(
array('user_id'=>$head->user_id, 'role_id'=> ),
array('user_id'=>$head->user_id, 'role_id'=> $head->project_owner_id),
//...
);
MappingTable::insert($data); // Eloquent
DB::table('role_mapping table')->insert($data); // Query Builder

Laravel SELECT SUM 2 columns Eloquent

SELECT
SUM(username = 'benjamin') as c1,
SUM(email = 'benjamin#hotmail.com') as c2
FROM users WHERE active = 0
I have a mysql query need to check 2 columns match
But now I need to write it into Laravel Eloquent
anyone know how to do this in Eloquent?
You can do it like this:
User::where('active', 0)
->select(DB::raw("SUM(username = 'benjamin') as c1, SUM(email = 'benjamin#hotmail.com') as c2"))
->get();
Hope this helps!

Can't retrieve records using foreign key on the same table in Laravel 5.2

I'm using Laravel 5.2 to retrieve records from a database.
My table (simplified):
services:
id
name
parent_id
parent_id is FK to the same table (FK to services.id).
This code returns an empty collection:
$category->services->where( 'parent_id', 0 )
Select with other where condition works properly. ex.
$category->services->where( 'name', 'foo )
returns not empty results.
Raw SQL works fine too:
SELECT * FROM services WHERE parent_id = 0;
What is wrong with Eloquent or how to use it in a way where I can retrieve records with concrete parent_id ?
Your query should be like this:
$services = $category->services()->where('parent_id', 0)->get()

Laravel: Get not related items in a many to many relation

Is it possible to get all items not related to the specific instance, in a many to many relation in Laravel?
Example:
I have two models, User and Pet. They have a many to many relationship, because a User can have many pets, but a pet can belong to more users.
But I want a list of pets, which a specific user is not having.
How is that possible?
EDIT
The above is just an example, so not related to my current task. Just more simple to explain with users and pets. But to specify:
PETS TABLE:
ID TYPE
1 Dog
2 Cat
3 Rabit
4 Horse
5 Rat
6 Bat
7 Bird
USERS TABLE:
ID NAME
1 Martin
2 Peter
3 Viggo
PET_USER TABLE:
ID PET USER
1 1 1
2 3 1
3 5 1
Then Martin has a dog, a rabbit and a rat.
But I want a list of pets, that he does not have:
Cat, horse, bat and bird
You may try this (your question sounds a little confusing to me tho):
$pets = Pet::with('users')->whereDoesntHave('users', function($query) use ($id) {
$query->where('users.id', $id);
})->get();
Also, try this as well (if you want):
$pets = Pet::with('users')->whereHas('users', function($query) use ($id) {
$query->where('users.id', '!=', $id);
})->get();
There is no function from laravel to run this out of the box.
You have to join this manually:
$pets = Pet::leftJoin('pet_user', function($join) use ($userId){
$join->on('pets.id', '=', 'pet_user.pet_id');
$join->on('pet_user.user_id', '=', \DB::raw("'".$userId."'"));
})->whereNull('pet_user.pet_id')->get();
i would suggest this method if you already defined ManyToMany relationship on your models :
$user = User::find($user_id);
$pets = new Pet;
$exception = $user->profile->pluck('id')->toArray();
$pets = $pets->whereNotIn('id',$exception)->get();
My Solution: worked for me atleast.
Just use :
Pet::whereDoesntHave('user');
or
Pet::whereDoesntHave('user', function($qu) {
// ...(extended query filter logic)
});

Returning full duplicate rows using Laravel's query builder

I am looking to return the full information on duplicate records from my table.
I am currently using the following:
DB::table($entity['table'])
->select('*')
->groupBy($entity['columns'])
->havingRaw('COUNT(*) > 1')
->get();
Which is great, it returns the duplicate records, however, this only returns one of the records I need to return all the duplicates so that I can greet the user with a choice on which one to delete or keep.
How can I modify the above query to accomplish that?
Joining against the same table will allow you to retrieve the duplicate records without just getting a single version of it (caused by your groupBy in your question)
$entity['columns'] = ['username', 'surname'];
$groupBy = implode(',', $entity['columns']);
$subQuery = DB::table('list')
->select('*')
->groupBy($groupBy)
->havingRaw('(count(id) > 1))');
$result = DB::table('list')
->select('*')
->join(
DB::raw("({$subQuery->toSql()}) dup"), function($join) use ($entity) {
foreach ($entity['columns'] as $column) {
$join->on('list.'.$column, '=', 'dup.'.$column);
}
})
->toSql();
// or ->get(); obviously
dd($result);
You need to join back to the table in $entity['table'] on the columns in the $entity['columns'] to get the duplicates.
Also, the select('*') is not really a good idea even if you are using mysql. This is against the sql standard and works in mysql only if it is configured in a certain way. If the configuration changes or you migrate your app to a mysql server with different configuration on sql modes, your query will fail.
I would use $entity['columns'] in the select list as well.
In sql the query should look like as follows:
select table.* from table inner join
(select field1, field2 from table t
group by field1, field2
having count(*)>1) t1
on table.field1=t1.field1 and table.field2=t1.field2
You can accomplish this by using whereIn and a function to query the same table that you are working with.
Let say you have a scenario where you want to look for duplicate records containing the same last name in the user table.
Database Table - User
--- user_id --- first_name --- last_name --- email ---
1 Dan Smith dan#test.com
2 Jim Jones jim#test.com
3 Amy Grant amy#test.com
4 Bob Brown bob#test.com
5 Sue Davis sue#test.com
6 Leo Grant leo#test.com
7 Ann Grant ann#test.com
Then you can use the following code;
$duplicates = DB::table('user')
->select('user_id', 'last_name')
->whereIn('user_id', function ($q){
$q->select('user_id')
->from('user')
->groupBy('last_name')
->havingRaw('COUNT(*) > 1');
})->get();
Which will return the following;
--- user_id --- last_name
3 Grant
6 Grant
7 Grant

Categories