query in table pivot laravel - mysql

I have two tables and one pivot table which has
FK_idStore
FK_idEmployee
dateChange
My model store:
public function employee(){
return $this->belongsToMany(empleado::class,'employee_store', 'fk_idStore','fk_idEmployee')
->withPivot('dateChange');
}
the result:
I need to show the last store where an employee was.

Try:
$store = Store::findOrFail($id)->employee->latest();
Or:
$store = Store::findOrFail($id)->employee->->sortBy('dateChange', 'desc')->first();

Assuming the pivot table is the Store, and that you need the last record of each employee in each store, use:
public function employee(){
return Employe_Store::all()->groupBy('fk_idEmployee')->max('dateChange');
}

Related

convert sql query (join) in laravel query builder

I want to do this request with laravel ( i have 3 tables users , userprojet and projets ) users hasmany projets and projet hasmany users that's why i do another table userprojet to join the two table
and now i try to extract the projet of a specific user with this request
select projets.*
from projets p
, userprojet up
, users u
where p.id= up.projet_id
and up.user_id = u.id
and user_id = 2;
I need help please.
You can try this:
$users = DB::table('projets')
->join('userprojet', 'projet_id.id', '=', 'userprojet.projet_id')
->join('userprojet', 'users.id', '=', 'userprojet.user_id')
->select('project.*')
->where('userprojet.user_id', 2)
->get();
References:
Laravel -> Queries -> Joins
You can also define many to many relationship in your models instead of writing queries every time
// User model
public function projets()
{
return $this->belongsToMany(Projet::class, 'userprojet');
}
// Projet model
public function users()
{
return $this->belongsToMany(User::class, 'userprojet');
}
// in controller
$user = User::first(); // for example
dd($user->projets);
// with eager loading
$user = User::with('projets')->first();
dd($user->projets);

Join 3 tables based on column values - Laravel

LEADS TABLE
id
title
owner_id
from_table
EMPLOYEE TABLE
id
first_name
last_name
role
ADMIN TABLE
id
first_name
last_name
role
$users = Leads::query();
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
if($user->from_table == 'employee'){
$emp = Employee::where('id',$user->owner_id)->first();
return $emp->first_name.' '.$emp->last_name.' ('.$emp->role.')';
}
if($user->from_table == 'admin'){
$admin = Admin::where('id',$user->owner_id)->first();
return $admin->first_name.' '.$admin->last_name.' ('.$admin->role.')';
}
})
the above solutions is working fine but we are unable to search column wise induvidual searching in datatables.
what i want is join query something like:
if(leads.from_table == employee)
// fetch data from EMPLOYEE TABLE i.e. LEADS TABLE + EMPLOYEE TABLE
id
title
owner_id
from_table
first_name
last_name
role
if(leads.from_table == admin)
// fetch data from ADMIN TABLE i.e. LEADS TABLE + ADMIN TABLE
id
title
owner_id
from_table
first_name
last_name
role
I think you should change your database structure to use polymorphic relations, they fully comply with your needs - https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships
from_table column should contain the class name of the parent model.
Add in Leads model
public function fetchOwner()
{
return $this->morphTo();
}
Add In Employee Model
public function employee()
{
return $this->morphOne('App\Employee', 'fetchOwner');
}
Add In Admin Model
public function employee()
{
return $this->morphOne('App\Admin', 'fetchOwner');
}
$users = Leads::with('fetchOwner');
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
return $user->fetchOwner->name;
})
thanks to all who tried to help..
I'm answering my own question as i found the answer after 9 days digging everywhere..
so here is the answer:
you may want to replace owner_code by owner_id in your business table.
so i changed the from_table to owner_type & owner_type now should contain the class name as value ex: changed admin to App\Admin & employee to App\Employee in Database
App\Admin.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Employee.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Leads.php
public function owner()
{
return $this->morphTo();
}
Thanks to: laravel morphTo how to use custom columns? (EddyTheDove) for pointing out the exact problem..

Compare two fields within different table using Laravel

I have two tables employees and customers , i've gave the schema below.
Customers('id' , 'username', 'location');
Employees('id' , 'EmployeeID' , 'CustomerID', 'location');
Currently I can use a query to retrieve customers details like the below query , note this is when the user is logged into the system hence the Auth::
$customerQuery1 = DB::table('customer')
->where('id', '!=', Auth::id())
->where('item', '=' , Auth::customer()->recommendation)
->get();
Each Employee has many customers ,I want other customers to see other customer items so i have attach the CustomerID field which is a foreign key and relates to the id field within the Customer table.
I've tried something like the below however I think I may need a join query but i'm unsure.
$query2 = DB::table('Customer','Employee')
->select('username')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
$query2 = DB::table('Customer')
->select('username')
->join('Employee', 'Customer.id', '=', 'Employee.CustomerID')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
I am then returning the values to my blade file like the below
return view ('pages.dashboard')
->with('query1',$query1)
and then Im using php indentation within my blade file to return the users data
#foreach ($query1 as $Userfound)
{{ $Userfound->username}}</p>
#endforeach
Actual Query needed in plain english
so I need to select a customer , where CustomerID == id
NOTE: id is from the customers table, CustomerID stored in the Employees table.
You can create Models using Laravel, for example:
Employee.php
public function customers()
{
return $this->hasMany('App\Customer');
}
Customer.php
public function employee()
{
return $this->belongsTo('App\Employee');
}
Which you can access like so:
$customer = Customer::where('id',Auth::user()->id)->firstOrFail();
or
$employee = Employee::where('id',Auth::user()->id)->firstOrFail();
And to see an employee's customers:
$employee->customers()->get();
Or to see the other customers of $customer's employer:
$customer->employee()->customers()->get();

How to use FIELD() function of mysql in JPA

My sql query is something like
Select * from tableA order by FIELD('ID', 3, 5, 2)
How do I implement this in JPA using criteria builder?
EDIT
List<Integer> ordList = new ArrayList<Integer>();
ordList.add(3);
ordList.add(5);
ordList.add(2);
public List<Order> getOrderBys(CriteriaBuilder cb, Root<?> root) { 
List<Order> orders = new ArrayList<Order>();         
orders.add(cb.function("FIELD", Integer.class, root.get("id"), ordList));
     return orders; 
}
Above is my function which gives list of oders, I want to add only one order same as above sql query. How can I add/call that function in orders.add() method? The above method gives error.
We can use with the native query flag.
For example.,
#Query(value="select * from table_name where id IN :id ORDER BY FIELD(id,:id)",nativeQuery = true)
List<Entity Name> getByIds(#Param("id") List<Integer> id);
For that simple case I would not use the FIELD function but would sort the result by the sorted list, as described here.
E.g.:
List<Integer> ordList = new ArrayList<Integer>();
ordList.add(3);
ordList.add(5);
ordList.add(2);
List<Entity> resultList = query.getResultStream()
.sort(Comparator.comparing(entity -> ordList.indexOf(entity.getId())))
.collect(Collectors.toList();

Zend_Db: How to get the number of rows from a table?

I want to find out how many rows are in a table. The database that I am using is a MySQL database. I already have a Db_Table class that I am using for calls like fetchAll(). But I don't need any information from the table, just the row count. How can I get a count of all the rows in the table without calling fetchAll()?
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
Counting rows with fetchAll considered harmful.
Here's how to do it the Zend_Db_Select way:
$habits_table = new Habits(); /* #var $habits_table Zend_Db_Table_Abstract */
$select = $habits_table->select();
$select->from($habits_table->info(Habits::NAME), 'count(*) as COUNT');
$result = $habits_table->fetchRow($select);
print_r($result['COUNT']);die;
Proper Zend-Way is to use Zend_Db_Select like this:
$sql = $table->select()->columns(array('name', 'email', 'status'))->where('status = 1')->order('name');
$data = $table->fetchAll($sql);
$sql->reset('columns')->columns(new Zend_Db_Expr('COUNT(*)'));
$count = $table->getAdapter()->fetchOne($sql);
This is how it's done in Zend_Paginator. Other option is to add SQL_CALC_FOUND_ROWS before your column list and then get the number of found rows with this query:
$count = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()');
You could do a
SELECT COUNT(*)
FROM your_table
$dbo->setFetchMode( Zend_Db::FETCH_OBJ );
$sql = 'SELECT COUNT(*) AS count FROM #table';
$res = $dbo->fetchAll( $sql );
// $res[0]->count contains the number of rows
I'm kind of a minimalist:
public function count()
{
$rows = $db->select()->from($db, 'count(*) as amt')->query()->fetchAll();
return($rows[0]['amt']);
}
Can be used generically on all tables.
Add count capability to your Zend_DB Object To count all table rows
public function count()
{
return (int) $this->_table->getAdapter()->fetchOne(
$this->_table->select()->from($this->_table, 'COUNT(id)')
);
}