B
B
Berkutman2020-08-16 18:52:26
Laravel
Berkutman, 2020-08-16 18:52:26

How to access a specific table through a model in laravel 7?

Model - Shop.php
Controller - ShopController.php

Shop.php

class Shop extends Model
{
protected  $table='product';
  protected $connection = 'sqlsrv2';
}

ShopController.php
use App\Shop;
use DB;
class AdminPanelController extends Controller
{ 
 public function adminshop() {
 //return view("admin", ['item' => Shop::all()->toArray()]);
 DB::connection('sqlsrv2')->table('product')->get()->toArray();
 }
}


How do I access a specific table through a model?
Now I use either Shop::all(); , but it only refers to protected $table='product';
To access other tables from the database I use

DB::connection('sqlsrv2')->table('product')->get();

But I would like to use the syntax ModelName::tablename();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2020-08-16
@Berkutman

The model is not a universal facade for accessing the database, the "one model - one table" approach is correct in most cases, if different tables are connected by one-to-one, one-to-many, many-to-many relationships, then for this laravel also has tools to get related data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question