make union in laravel as a database table - php

I have this code in a laravel project
$state_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->state($state_id);
$city_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->city($city_id);
$district_query = Advertisement::active()
->notExpired()
->inTime()
->network($network)
->textbook($textbook, $textbook_category_id, $book_category_id)
->grade($grade)
->district($district_id);
$result = $state_query
->union($city_query)
->union($district_query);
now, I want to make "$result" variable as a database table and use "where" and "sum" eloquent functions on it
how can I do that?

Simply make a collection :
https://laravel.com/docs/5.3/collections
The results of Eloquent queries are always returned as Collection instances.

Related

Yii2 How to get all values from column (DB)

I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();

Laravel: How to get Models out of query results?

Suppose I have a query that, among other things, returns user id's, this query was built using DB::table()... rather than using the models, so, as a result, I got a collection with arrays for each retrieved row, something like this:
user_id | calculated_data
--------+----------------
1 | 123
2 | 111
3 | 222
... | ...
Supose I store this collection on a $data variable, of course if I do a foreach ($data as $d) { $d->user_id ... } will work.
But I want this query to return something more like what the ORM does, so instead user_ids, return User models so I can do, for example, a $data->user->name
Can this be even done? if so, how?
You can use the hydrate() function, it accepts an array of stdClass objects (or even associative arrays AFAIR) as input and returns a collection of Eloquent Models, so you can do things like this:
$result = DB::table('users')->take(10)->get();
$users = App\User::hydrate($result->all());
You can even get a collection of Eloquent Models directly from a RAW query with the fromQuery() function, i.e.:
$users = App\User::fromQuery('SELECT * FROM users WHERE id > ?', [2])
Update: If in your collection you don't have all the fields to hydrate a model, you can preload all the users you need with one query and modify your collection, i.e.:
$users = App\User::find($data->pluck('user_id'));
$data->transform(function($item) use($users) {
$item->user = $users->where('id', $item->user_id)->first()
return $item;
});
You need to use Eloquent to call value the "ORM way" I did not find anything related to the query builder in relation to ORM.
You could do something like this:
$flights = App\Flight::all();
foreach ($flights as $flight) {
echo $flight->name;
}
And in the ORM way you would get the user like this:
foreach ($flights as $flight) {
echo $flight->user->name;
}
Of course you would need to setup the correct relations.
// initial query will return collection of objects
$query = DB::table('user_something')
->join('users', 'users.id', 'user_something.user_id');
// You could cast it to the model query, by using fromSub.
// Make sure to alias a subquery same as the model's name,
// otherwise it would not be able to parse models data
User::fromSub($query, 'users');
// The most robust way is to get table name from the model
User::fromSub($query, User::make()->getTable());

Data comparison in laravel

I'm beginner in laravel and I'm trying to run comparison queries given in the database.
I saved a field date that is implemented by a form together with other fields including the name.
I tried to query the name and it works all regularly with this code below.
I would like to retrieve all the rows that have the name variable as the field name that I pass (and here it seems to work) and then only those with the field date that have the specified month at the number that I pass as variable $month.
what would be the right form to do this?
thanks
Piero
public function filterparamenter(){
$name = request('name');
$month = request('$month');
$query = subagente::all();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.
Using ::all() returns a Collection, which has a ->where() method, but ->whereMonth() is only available on Eloquent's Builder class. Change your code as follows:
$query = subagente::query();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Or, more compact:
$results = subagente::where("subagente", $subagente)
->whereMonth("data", $month)
-get();
Using ::query() or ::where() to start your query will generate a Builder instance, which you can chain addition clauses (->where(), ->whereMonth(), etc) on before calling ->get() to return a Collection of subagente records.
Side note, should "data" be "date"?

How to write SQL query for yii2 ? "InnerJoin"

SQL query:
SELECT * FROM bd.group
INNER JOIN bd.account2group ON bd.group.id = bd.account2group.group_id
INNER JOIN bd.account ON bd.account2group.account_id = bd.account.id
WHERE bd.group.id = 8
How will it be in yii2?
There are multiple ways to get to this query using Yii2. You should probably be able to get to all these solutions by reading the docs. At https://www.yiiframework.com/doc/guide/2.0/en the 'Working with databases' should give you more than enough examples to get at least something working.
If you want to use the QueryBuilder from Yii2 it will look like this:
$query = (new \yii\db\Query)
->from('bd.group')
->innerJoin('bd.account2group', 'bd.group.id = bd.account2group.group_id')
->innerJoin('bd.account', 'bd.account2group.account_id = bd.account.id')
->where([
'bd.group.id' => 8,
]);
Then you can call $query->all(), $query->one(), or one of the other functions that the Query class holds. Check out https://www.yiiframework.com/doc/api/2.0/yii-db-query for all possible options.

How to fetch an object from a oneToMany relationship using createQuery()

My structure is as simple as
One user -> has many notifications
so to fetch the notifications of the logged in user
I type this on the controller
$notifications = $this->getUser()->getNotifications();
Now I need to paginate the results but since this won't work
$notifications = $this->getUser()->getNotifications()->setMaxResults(2)..
I guess I need to use a createQuery to fetch the results?
what query would be the DQL equivalent of
"$this->getUser()->getNotifications()" ?
You can't limit . Try slice
If you have Doctrine 2.1 you can use ->slice() on the collection:
$notifications = $this->getUser()->getNotifications();
$result = $notification->slice(0, 2);

Categories