Laravel select table fields by using variables - laravel

I want to fetch selected fields from my tables in laravel for that I assign my table fields in a variable. But always it gives me some database query error, here I added my code for that. This working fine when I use direct fields instead of them assign into a variable
$selectedfields = "'table1.*', 'table2.*','table3.column'"
$data = DB::table('table1')
->select($selectedfields)->get();

You can use DB:raw:
$selectedfields = 'table1.*, table2.*, table3.column';
$data = DB::table('table1')
->select(DB::raw($selectedfields))->get();
You might need to join table as well.

your query should be like this
$data = DB::table('table1')
->join('table2','table2.id','=','table1.id')
->join('table3','table3.id','=','table1.id')
->select('table1.*','table2.*','table3.*')->get();

Related

Problem trying to insert a value from a query with eloquent

i'm trying to select and insert values into a database with eloquent models. The thing is, i made a query to get a value from another table and insert it in the new one. But it keeps inserting 0 when it should insert the value of the id that i'm retrieving
This is the way i'm selecting the id from table clients:
$client_id = Client::select('id')->where('dni', '=', $request->client)->first();
\Log::debug($client_id);
The debug on the Log returns this:
[2020-08-05 17:43:25] local.DEBUG: {"id":1}
And this is the insert:
$seguro = new Seguro();
$seguro->usuario_id = $user_id;
$seguro->cliente_id = $client_id;
$seguro->save();
And the insert is successfull except for the column cliente_id where i'm getting 0 instead of 1.
Can anyone help me with this?
Your $client_id contains object (model), not integer value. You can even see this in debug. Just get id from this model using ->id
$seguro->cliente_id = $client_id->id; // also better change name $client_id to $client
or
$client_id = Client::select('id')->where('dni', '=', $request->client)->first()->id;
Also it is good idea to write code in english (variable names). For example I do not know what "dni" should mean in this query.

Getting data from multiple tables via Laravel Eloquent

I have three tables; rate_params, review_form_languages, and review_form_translations. And corresponding models RateParam, ReviewFormLanguage and reviewFormTranslation.
rate_params has columns id, info_message, order and validation.
review_form_languages has id and name
review_form_translations has id, rate_params_id, review_form_languages_id, and text.
I would like to have query that fetches all the data from rate_params and the text from review_form_translations where review_form_languages.name is the passed parameter.
I have a query that fetches all the data from RateParam model as below
$reviewForm = RateParam::select(
'rate_params.id',
'rate_params.validation',
'rate_params.info_message',
)->orderBy('order', 'asc')->get()->toArray();
How do I join to get the text from review_form_translations where review_form_languages.name is the passed parameter?
Can you try this ,
use DB; // Top of the file
$reviewForm = DB::table('rate_params')
->join('review_form_translations','rate_params.id','=','review_form_translations.rate_params_id')
->join('review_form_languages','review_form_languages.id','=','review_form_translations.review_form_languages_id')
->orderBy('rate_params.order', 'asc')
->get()
->toArray();

How can I write this query using the laravel query builder?

I'm on laravel 5.1 using postgres as the DB. I have a fiddle here in case it helps understand my issue: https://www.db-fiddle.com/f/5ELU6xinJrXiQJ6u6VH5/4
with properties as (
select
properties.*,
json_agg(property_fields.*) as property_fields
from
properties
left join fields as property_fields
on property_fields.parent = 'property' and property_fields.parent_id = properties.id
group by properties.id, properties.deal_id, properties.address
)
select
deals.*,
json_agg(properties.*) as deal_properties,
json_agg(deal_fields.*) as deal_fields
from deals
left join properties on deals.id = properties.deal_id
left join fields deal_fields on deal_fields.parent = 'deal' and deal_fields.parent_id = deals.id
group by deals.id, deals.name
order by deals.id
Writing most of this is fairly straight forward. The problem I'm having is with the with properties as (...) block. I've tried something like:
DB::statement('WITH properties AS ( ... )')
->table('deals')
->select(' deals.*, json_agg(properties.*) as deal_properties, ')
...
->get();
But I notice the execution stop after DB::statement()
Is there a method in the Query Builder that I'm missing? How can I prefix my query with the WITH properties AS (...) statement?
I think it should also be noted that I'm trying to implement a Repository Pattern and I can't just wrap a DB::statement() around the whole query.
I've created a package for common table expressions: https://github.com/staudenmeir/laravel-cte
$query = 'select properties.*, [...]';
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
You can also provide a query builder instance:
$query = DB::table('properties')
->select('properties.*', [...])
->leftJoin([...])
->[...]
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
if you want some data fetch from a table you can use this type of code
$user = DB::table('table name')->where('name', 'John')->where('height','!>',"7")->select('table fields which you want to fetch')->get();
Or try using the larevel Eloquent ORM which will make things easier with the database.
for more example or reference
https://laravel.com/docs/5.0/queries
I think you can actually do this with eager loading,
assuming that the relationships are set up correctly.
(More reading here: https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads)
So I think you'd be able to add something like
->with(['properties' => function ($query) {
$query->select('field')
->leftJoin('join statement')
->groupBy('field1', 'field2');
}])

Select one column with where clause Eloquent

Im using Eloquent. But I'm having trouble understanding Eloquent syntax. I have been searching, and trying this cheat sheet: http://cheats.jesse-obrien.ca, but no luck.
How do i perform this SQL query?
SELECT user_id FROM notes WHERE note_id = 1
Thanks!
If you want a single record then use
Note::where('note_id','1')->first(['user_id']);
and for more than one record use
Note::where('note_id','1')->get(['user_id']);
If 'note_id' is the primary key on your model, you can simply use:
Note::find(1)->user_id
Otherwise, you can use any number of syntaxes:
Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first();
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple
Also note, in any of these examples, you can also just assign the entire object to a variable and just grab the user_id attribute when needed later.
$note = Note::find(1);
// $user_id = $note->user_id;

How to use 'IN (1,2,3)' with findAll?

I need to get a couple of Students from the database, and I have their primary keys in a comma-separated string.
Normally using SQL it would be something like:
$cleanedStudentIdStringList = "1,2,3,4";
SELECT * FROM Student WHERE id IN ($cleanedStudentIdStringList)
Yii's ActiveRecord seems to insert a single quote around bound parameters in the resulting SQL statement which cause the query to fail when using parameter binding.
This works, but doesn't use safe parameter binding.
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
Is there a way to still use parameter binding and get only a couple of rows in a single query?
You can do it also that way:
$criteria = new CDbCriteria();
$criteria->addInCondition("id", array(1,2,3,4));
$result = Student::model()->findAll($criteria);
and use in array any values you need.
Aleksy
You can use findAllByAttributes method also:
$a=array(1,2,3,4);
$model = Student::model()->findAllByAttributes(array("id"=>$a));

Resources