How to use query builder to retrieve array values from different tables? - php

Following is the code snippet that I have used in my controller:
public function index(Request $request)
{
$query = DB::table('project_files')->select('project_id')->get()->toArray();
dd($query);
return view ( 'filesync/listfiles' )->with ( $query);
}
So when I try passing the values into the view, I get an array which consists of the project_id from the project_files table. What I would want to do now is to retrieve the project_names of these project_ids, stored in the projects table.I need to use the project_id for the same , but am unable to understand how to relate these using query builder.Any help would be appreciated, meaning how do I use the array values in the query retrieving project names from projects table.

You can setup relationships which is the ideal way or you can use a leftJoin with your query:
DB::table('project_files')->select('project_files.project_id')->leftJoin('projects', 'project_files.project_id', '=', 'projects.project_id')->get()->toArray();
and replace the column name respectively to the correct values.
Another suggestion I would make is to actually make use of the M in MVC by defining models for your table instead of using the db facade.
Note: Don't forget to include the columns you wish to select within your select function.

Related

Cakephp - get database data from not associated models

I wanted to ask, how can i get data from one table and use this in other find.
For example, i have films table.
I want to get highest rated 3 films. Result should return 3 ID's.
Now, i want to create other query from not associated table, and pass this 3 ID's as "conditions" to find data in other table.
I dont want to use associations, because, data is stored in many databases, and this is problematic.
Thank You.
Once you've got your film IDs you can use in to filter the results from your other Model:-
$filmIds = ['32','55','75'];
$query = TableRegistry::get('Model')->find()
->where(function ($exp, $q) use ($filmIds) {
return $exp->in('film_id', $filmIds);
});
// WHERE film_id IN ('32','55','75')
Check out the docs section on advanced conditions.
If you need to get your film IDs into the correct format (i.e. that shown in the example code) you can use Hash::extract() on the results from your previous query.
if your cakephp version 3.x you can use subqueries in fairly intuitive way
$films = TableRegistry::get('Films')->find('highestRated')
->select(['id'])
->limlt(3);
$query = $related->find()
->where(['id' => $films]);
Subqueries are accepted anywhere a query expression can be used. For example, in the select() and join() methods. http://book.cakephp.org/3.0/en/orm/query-builder.html#subqueries

Codeigniter Aliase not working in Views

I wrote a lot of code in codeigniter but I had to restructure my database column prefixes and when I use join queries to join some of my tables in my model's queries there is some tables in one query that have the same id column , I used Alias 'As alias1' for a table name, and model runs successfully without problem
but when I pass the $q = $this->db->get() variable to my controller and then pass it to my view and iterate it like this :
foreach($q->result() as $res)
echo $res->alias1.id;
php errors that unknown $alias1.id but I declared alias1 for one of my tables.
whats the problem ?
Thanks
When you do ->result(), CI will build an array of objects.
Each column declared in your select will be an object member. However, the aliases are not preserved.
It means that SELECT alias.field will be converted as $obj->field not $obj->alias.field.
If you have two fields which have the same name, set an alias inside your SELECT clause
$this->db->select("alias1.field as myfield, alisas2.field as myotherfield");
Then you will be able to get them with $obj->myfield and $obj->myotherfield

Laravel 4 Query groupBy: all columns from table

I have to call the $model->groupBy(?allcols?) function with all columns as a param.
How should I do this?
Edit: I have all Columns as an Array, so i can't pass them like 'col1','col2',...
I'm asking this because i have this poblem (github) and i found out, that there the prob is on Line 119.
I tried it manually like col1,col2 which worked, but it should by dynamically for all models.
I found this snippet, to get all cols from the current table as an array, but i can only pass a String.
Ok, if I'm understanding your edit correctly, you've got an array of column names you wish to group by. If $model is the name of your query, I'd recommend just using a foreach loop and appending each field:
foreach($allcols as $col){
$model->groupBy($col);
}
$model->get();
There is no such function for grouping all columns but you may use groupBy(col1, col2, ...), for example, if you have a posts table then you may use:
DB::table('posts')->groupBy('col1', 'col2')->get();
Or using Eloquent Model, for example a Post model:
Post::groupBy('col1', 'col2')->get();
If all you're trying to do is get rid of duplicate records (which is all that groupBy(all) would do as far as I can envision), you could also just use $model->distinct() instead. However, unless you add a select() to exclude the id field, you're going to wind up with the full recordset with no grouping, as by definition the id is unique to each record and thus won't collapse across records by either manner.

relational query in yii

I have two models named Statement.php and Images.php
In my statement.php model i have a relation saying
'images'=>array(self::HAS_MANY,'Images','statement_id'),
you know what i mean by this line,
Now , i want to execute this relational query ,
$data = Statement::model()->with('images')->findall($criteria);
this query only returns the columns of Statement table not the Images table why?
how you take pictures? example $data->images->id
If you have made sure that there is data in the Images table then
$data = Statement::model()->with('images')->findall($criteria);
will give you the desired output.
Now if you want to access the Images table data then for that you will have to use
$data->images
You cant access the Images data directly.For that you will have to use the relation name.

Searching and filtering / refining database results in Laravel 4

I'm looking for a way to search and filter a database table / Eloquent model through the query string in Laravel 4.
I have a table named houses with the columns named: price, name, hasCoffeeMachineand hasStove
I want the user to be able to do something like: http://example.com?name=test&hasCoffeeMachine=1
Which will get all the rows where the name is "test" and they have a coffee machine.
I want the user to be able to add URL parameters based on the filter they desire. What is the best way to account for all the possible combinations of query strings to return the correct results from the table?
$houses = new House;
if(Input::get('name'))
$houses->where('name', '=', Input::get('name'));
if(Input::get('hasCoffeeMachine'))
$houses->where('hasCoffeeMachine', '=', Input::get('hasCoffeeMachine'));
// Keep adding more for every filter you have
// Don't do this till you are done adding filters.
$houses = $houses->get();
alternatively you could build and pass in an array into the where clause https://laravel.com/docs/5.2/queries#where-clauses
$houses = $houses->where([
['hasCoffeeMachine',1],
['price','<','1000'],
])->get();
You can build your array with any conditional statements.

Categories