Laravel query builder duplicates row - php

I'm printing some data in mi index.blade.php file but it returns duplicated values. This is my query:
$hist = DB::table('codigo_sisnova')
->join('llamada', 'codigo_sisnova.idPaciente', '=', 'llamada.id_paciente')
->join('medico', 'llamada.id_medico', '=', 'medico.id_medico')
->where('llamada.status_llamada', 'Finalizada')
->where(function($query){
$query->where('llamada.status_pago', '=', 'Sisnova')
->orWhere('llamada.status_pago', '=', 'RedireccionadaSisnova');
})
->distinct()
->get();
I already tried with unique() but it doesn't work too.
EDIT
The relations between tables are one to may from "codigo_sisnova" to "llamada", if I take out the join with the table "medico" the rows keep duplicating
Every row gets a duplicate

You will have multiple codigo_sisnova rows if you are joining tables that have multiple matches on that table. DISTINCT would not eliminate those since the joined data will make it non-distinct in those results. I would recommend trying to use groupBy() to eliminate the redundant rows.

You are missing the group_by statement. Assuming that you have an ID column in codigo_sisnova, besides adding it in a SELECT clause, you need to add it before your get() method :
$hist = DB::table('codigo_sisnova')
->select('codigo_sisnova.id')
->join('llamada', 'codigo_sisnova.idPaciente', '=', 'llamada.id_paciente')
->join('medico', 'llamada.id_medico', '=', 'medico.id_medico')
->where('llamada.status_llamada', 'Finalizada')
->where(function($query){
$query->where('llamada.status_pago', '=', 'Sisnova')
->orWhere('llamada.status_pago', '=', 'RedireccionadaSisnova');
})
->group_by('codigo_sisnova.id')
->get();

Related

Laravel get one to many with limit by DB query builder

I have a products table that is connected through model_has_attachments with attachments table. I need to connect first attachment to each product record thought the query builder, but for some reason it just give me few records with model_has_attachments ids and rest is the null
my query builder look as:
$products = DB::table('products')->
leftJoin(DB::raw('(select `model_id`, `attachment_id` from model_has_attachments where model_has_attachments.model_id = id) as model_has_attachments'), 'model_has_attachments.model_id', 'products.id')->
leftJoin('attachments', 'model_has_attachments.attachment_id', '=', 'attachments.id')->
select('products.id', 'products.square', 'products.height', 'products.address', 'products.rooms', 'products.title', 'products.description', 'model_has_attachments.model_id as id_model', 'model_has_attachments.attachment_id')->
where([
['products.deleted_at', '=', null],
]);
I've tried to add limit = 1 in the DB::raw but it just give me the first record of the products table, not a joined table. Can you tell me why?
I also tried different approach, but it takes all the record of attachments which result duplicate products records if product has more than one attachment. I also have tried to add ->limit(1) at the end but it just ignores the method.
leftJoin('model_has_attachments', function ($join) {
$join->on('products.id', '=', 'model_has_attachments.model_id')->where('model_has_attachments.model_type', '=', Product::class);
})->
``
//try this
$products = Product::leftJoin('model_has_attachments', 'products.id', '=', 'model_has_attachments.model_id')
->leftJoin('attachments', 'attachments.id', '=', 'model_has_attachments.attachment_id')
->addSelect('products.*', 'attachments.id as attachment_id')
->where('attachments.is_active',1)
->get();

Use query 2 in query 1 to get all data inside one query

I have 3 tables :
*hinteractions (id, name...)
*effects (id, name...)
*hinteractions_has_effects (hinteractons_id, effects_id)
I might have one to many effects in a hinteractions et one hinteraction might have one to many effects, that's why I have this join table.
I have this Eloquent query :
Query 1 :
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//I would like to use the query 2 here to select effects.name with hinteraction.id used in this query to get effects' name in this query (I might have one to many).
->get();
Query 2 :
$hinteractions_has_effects = DB::table('hinteraction_has_effects')
->select(DB::raw('effect_id, hinteraction_id','effects.name'))
->where('hinteraction_has_effects', '=', hinteraction.id (from the query 1))
->get();
With query 1, I retrieve some informations like hinteractions_id.
I would like to use those hinteractions_id and use them in the query 2.
The best way will be to merge both queries (1 and 2) to get only one Eloquent query.
Do you have any idea ?
Try below query and let me know if this is what you're looking for -
$informations_plante = DB::table('herbs')
->select('herbs.name as hname', 'herbs.sciname', 'herbs.id as herbid','hinteractions.id as hinteractionid','hinteractions.note as hinteractionnote','hinteractions.force_id','targets.name as targetname', 'forces.name as force_name', 'effects.id as effects_id', 'effects.name as effects_name')
->leftJoin('hinteractions', 'herbs.id', '=', 'herb_id')
->leftJoin('forces', 'forces.id', '=', 'force_id')
->leftJoin('targets', 'targets.id', '=', 'hinteractions.target_id')->where('herbs.id', $id)
//added below lines
->leftJoin('hinteraction_has_effects', 'hinteraction_has_effects.hinteractons_id', '=', 'hinteractions.id')
->leftJoin('effects', 'hinteraction_has_effects.effects_id', '=', 'effects.id')
->get();
HTH!

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

Eloquent - join clause with string value rather than column heading

I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.
I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.
The second $join statement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination' - ie, t1.parent_type should = a string value, Destination.
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->on('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Is it possible to force Eloquent to do this? I've tried replacing 'Destination' with DB::raw('Destination') but this does not work either.
Thanking you kindly.
Another best way to achieve same is :
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->where('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Replace your on with where
try using DB::raw("'Destination'")

Laravel 4: Query builder retrieve join table data

In Laravel, we could join 2 tables with this:
DB::table("users")->join('moreusers', 'users.id', '=', 'moreusers.user_id')->get();
And retrieve data with this:
$querydata[$i]->email
If both tables contain the same column name, how can I specifically retrieve it from first and second table?
Thanks.
Use select() method:
DB::table("users")
->join('moreusers', 'users.id', '=', 'moreusers.user_id')
->select('users.email as user_email', 'moreusers.email as other_email')
->get();

Categories