Query

Yuga's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform all database operations in your application.

Retrieving results from the database

Retrieving All Rows From A Table

You can use the table method on the DB class to begin a query. The table method returns a \Yuga\Database\Query\DB query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get or all methods:

<?php
namespace App\Controllers;

class UserController extends BaseController
{
    /**
     * Show a list of all of the users in the database.
     *
     * @return Response
     */
    public function index()
    {
        $users = \DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}

The get / all methods return a Yuga\Database\Elegant\Collection containing the results where each result is an instance of the PHP stdClass object. You may access each column's value by accessing the column as a property of the object:

Retrieving A Single Row / Column From A Table

If you just need to retrieve a single row from the database table, you can use the first / lastmethods. These methods will return a single stdClass object:

Aggregates

The query builder also provides a variety of aggregate methods such as count, max, min, avg, and sum. You can call any of these methods after constructing your query:

You can also combine these methods with other clauses:

Simple query: Get a user with the id of 3 . Note that null is returned when no match is found.

Full queries: Get all users with blue or red hair.

Select

We recommend that you use table() method before every query, except raw query(). To select from more that one table, pass an array of your tables instead of a plain string. But this is not a requirement as you can also pass in the different tables as below.

Method 1 (array)

Method 2 (tables as arguments)

Table alias

You can easily set the table alias as below:

You can change the alias anytime by using:

Output:

Multiple selects

Using select method multiple times select('a')->select('b') will also select `a` and b. This can be useful if you want to do conditional selects (within a PHP if).

Select distinct

Select from query

Items from another query can easily be selected as below:

Output:

Select single field

This can be done as below:

Select with sub-queries

Result:

You can also easily create a sub-query within the where clause as below:

Last updated

Was this helpful?