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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With