I am new in Laravel. I want to make some custom functions in models which is related to database query.
Class A Extends Controller{
public function view(){
B::get_user();
}
}
Class B Extends Model{
protected $table = "user";
public function get_user(){
//Here is my database query
}
}
How can I use database query in get_user() function? I know this method:
B::table('user')->get();
You can define query scopes for adding the query on the model as:
public function scopeUser($query)
{
return $query->where('some_field', 'some_value');
}
Then you can use it in you controller as:
B::user()->get();
Docs
Related
I'm working with too many mysql large views. I don't want to use Eloquent Model for the views.
I created "ViewBalance extends Illuminate\Support\Facades\DB". Everything worked as I wanted.
But i need to set init() method for company scope.
How can I use the global scope without init() method?
ViewModel
<?php
namespace App\Models\Views;
use App\Facades\CoreService;
use Illuminate\Support\Facades\DB;
class ViewBalance extends DB
{
const COMPANY_COLUMN = 'company_id';
const TABLE = 'view_balances';
public static function init()
{
return parent::table(self::COMPANY_COLUMN)
->where(self::COMPANY_COLUMN, CoreService::companyId());
}
}
In Controller
<?php
$data = ViewBalance::init()->get(); // Worked!
I have answered my own question. Because, I don't want to edit my question for more complicate. I want to talk about a solution to this problem.
I added $table_view variable and getView() method in Laravel model. If you want, you can create trait for clean codes.
It can be accessed easily views. Also it is part of the main model.
For example;
Laravel Basic Account Model
class Account extends Model {
protected $table = 'accounts';
protected $table_view = 'view_accounts';
public function getView()
{
return \DB::table($this->table_view)->where('global_scope', 1);
}
}
Laravel Account Controller
class AccountController extends Controller {
public function index()
{
$items = (new Account)->getView()->paginate(20);
}
}
public function scopeActive($query)
{
return $query->where('active', true);
}
or
public function scopeInactive($query)
{
return $query->where('active', false);
}
If I have below models:
class User extends Model{
protected $someDataFromExt = ['taskID0' => 'test', 'taskID1' => 'ting'];
public function tasks() { return $this->hasMany('Task'); }
}
class Task extends Model{
protected $appends = ['ext_data'];
public function user() { return $this->belongsTo('User'); }
public function getExtDataAttribute(){ return $this->external_data; }
}
I would like, when I do: $tasks = auth()->user()->tasks->all(); I want to pass $user->someDataFromExt (based on task ID) to task model, so I later in my $tasks variable I can access:
foreach($tasks as $task){
echo $task->ext_data;
}
Which will return data that was given from user model earlier?
Is this possible? how?
Not completely following why the task data is being stored on the user model, but I think what you’re asking can be achieved via your accessor method on your task model, providing you make the someDataFromExt public:
<?php
class Task extends Model {
public function getExtDataAttribute()
{
return $this->user->someDataFromExt['taskID' . $this->id];
}
}
Hello I´m writing an API and I want to display more information about the related model.
Routes.php
Route::resource('makes', 'MakesController');
MakesController.php
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->json($data);
}
}
This returns only information about the makes (id, name)
but how can I display also how many models has each make?
I have defined these two models
class Make extends Model
{
public function models()
{
return $this->hasMany('App\CarModel');
}
}
class CarModel extends Model
{
public function make()
{
return $this->belongsTo('App\Make');
}
}
You can define $visible field in the Make model's class like this:
protected $visible = ['models'];
This will automatically appends the related model's array to array/json.
You can also use an optional way with makeVisible method:
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->makeVisible('models')->json($data);
}
}
My Demo Controller (DemoController.php):
<?php
namespace App\Controller;
class DemoController extends AppController
{
public function users()
{
$this->loadmodel('registration');
$result = $this->registration->getAllUsers();
$this->set('user_data',$result)
}
}
?>
My registration model (registration.php):
<?php
namespace App\Model;
use Cake\ORM\TableRegistry;
class Registration extends AppModel {
$articles = TableRegistry::get('registration');
public function getAllUsers()
{
return $query = $articles->find();
}
}
?>
My View:
path -- src/Template/Demo/users.ctp
but it's getting error like this (in below image) --
Your model should be named RegistrationsTable, and be in src/Model/Table/RegistrationsTable.php. Load it with loadModel('Registrations'). (It's your entity that should be named Registration.) To use your custom finder method, name the function findAllUsers, fix the signature per the documentation (should take two parameters: Query $query, array $options) and call it as $this->Registration->find('all_users');.
And why are you trying to initialize a $articles variable as the registrations model inside the registrations model (but outside of any function)? So much mess...
I would like to set up a table prefix for all my models, since this is how it is designed in the database.
How can I achieve that?
You can override the getSource method to set the prefix:
class Users extends Phalcon\Mvc\Model
{
public function getSource()
{
return 'my_' . 'users';
}
}
Or, you can set a base model class to set the table prefix for all models:
class BaseModel extends Phalcon\Mvc\Model
{
public function getSource()
{
return 'my_' . strtolower(get_class($this));
}
}
and extend all models from that
class Users extends BaseModel
{
}
or in PHP 5.4 you can create a trait:
trait CustomPrefix
{
public function getSource()
{
return 'my_' . strtolower(get_class($this));
}
}
then in your model:
class Users extends Phalcon\Mvc\Model
{
use CustomPrefix;
}
Source
Also, if you have tables with underscores "_" you could write it like that:
public function getSource()
{
return 'my_'.strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', get_class($this)));
}
you can also add all your settings to initialize function. If you have any connection between models like one-one many-many one-many you will define them also in initialize method.
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setSource("the_robots");
}
}