Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel retrieve records from database using mysql view instead of the table itself

I know this is a simple question and I tried hard to search a solution for this. Maybe someone knows or experienced this already that might help me.

I am only a beginner in using Laravel please bear with me.

So I have this AgencyModel, the name of my table in the database is agency. And I have a MySQL view which is named view_agency, this contains the inner join of the agency table and other tables that has connection with it.

Model (This is the working code)

  protected $table = 'agency';

The records displays when I use the agency as the table name

But MySQL view table view_agency does not display/retrive the records from the database.

Model (This code is not working)

protected $table = 'view_agency';

I have a suspicion that the laravel eloquent might have to do with this, because $table is only being accepted and not mysql view.

use Illuminate\Database\Eloquent\Model;

Thanks...

like image 982
codeseeker Avatar asked Nov 07 '22 10:11

codeseeker


1 Answers

In SQL, a view is a virtual table based on the result-set of an SQL statement.

And you can get datas from view just like table's datas:

select * from view_agency

So you can use Laravel query builder or Eloquent builder to query records like table,

Laravel will convert the query builder or Eloquent to sql, so it will works:

DB::table('view_agency')->get();

I used do this before, I created a views/ directory inside the models/, and create the all views' files inside.

I think you can create that view model like this:

namespace App\Models\Views;

use Illuminate\Database\Eloquent\Model;
class ViewAgency extends Model {
}

However, I am following the laravel's way. I use the lowercase underscore plural form. So when I use ViewAgency, Laravel will find the table or view's name which is view_agencies:

ViewAgency::first();

It works fine.

And If you want to change the name, and I think there is no error with protected $table = 'view_agency;', You can try this way:

class ViewAgency extends Model {
    public function __construct()
    {
        $this->setTable('view_agency');
    }
}

This will work, too

like image 173
TsaiKoga Avatar answered Dec 04 '22 12:12

TsaiKoga