I have to override the method using
namespace common\models;
use Yii;
use yii\db\ActiveQuery;
class Addfindcondition extends ActiveQuery
{
public function init()
{
$this->andOnCondition([$this->modelClass::tableName() . '.branch_id' => Yii::$app->user->identity->branch_id ]);
parent::init();
}
}
And call the method in each model separately like this
public static function find()
{
return new Addfindcondition(get_called_class());
}
Now I want to override the find method globally. How it is possible that I dont need to use this static method in each model
You can override the find() method in case of ActiveRecord models, as you need to add this for all models you should create a BaseModel say
common\components\ActiveRecord or inside your models if you like
<?php
namespace common\components;
use yii\db\ActiveRecord as BaseActiveRecord;
class ActiveRecord extends BaseActiveRecord{
public static function find() {
return parent::find ()
->onCondition ( [ 'and' ,
[ '=' , static::tableName () . '.application_id' , 1 ] ,
[ '=' , static::tableName () . '.branch_id' , 2 ]
] );
}
}
And then extend all your models where you need to add this condition to the find() method, replace yii\db\ActiveRecord to common\components\ActiveRecord for instance if I have a Product Model and I want to add the conditions to it by default I will change the model from
<?php
namespace common\models;
use Yii;
class Product extends yii\db\ActiveRecord {
to
<?php
namespace common\models;
use Yii;
class Product extends common\components\ActiveRecord{
Related
This is my first time to try out Eager loading.
Here is my controller code.
I add 'WITH' into my code but I got this error
Call to undefined method Illuminate\Database\MySqlConnection::with()
I've been searching how to put WITH. but I've got error always. Could you teach me right code please?
class ProductController extends Controller
{
public function index(){
$products = Product::with(All());
$products = DB::with('products')
->join('creators', 'creators.id', '=', 'products.creator_id')
->join('categoris', 'categoris.id', '=', 'products.categori_id')
->join('branches', 'branches.id', '=', 'products.br_id')
->join('users', 'users.id', '=', 'products.user_id')
->get();
$data = array(
'title' => 'index',
'no' => 1,
'products' => $products,
);
return view('product.index',$data);
}
Update
Product
class Product extends Model
{
protected $fillable = ['title','kansu','creator_id', 'br_id','user_id' ,'categori_id'];
public function index()
{
return $this->belongsTo('Categori');
}
}
Categori
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categori extends Model
{
protected $fillable = ['pr_name'];
public function index()
{
return $this->belongsTo('Product');
}
}
UPDATE
the with eager loading is used with Laravel Eloquent.which means you first need define model like Product model here,and you need define relation between models like belongsTo hasMany.
for example
we had define two models Product and Category
we define the relation,Product belongsTo Category
then we can call Product::with('category') with eager loading
the DB:: method is only used in laravel database for lower level database operation,there is no model concept at DB:: method,you can directly use DB:: to construct the raw sql you want
the example of relation define
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['title','kansu','creator_id', 'br_id','user_id' ,'categori_id'];
public function categor(){
return $this->belongsTo(Categori::class);
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categori extends Model
{
protected $fillable = ['pr_name'];
public function products(){
return $this->hasMany(Product::class,'categor_id');
}
}
be aware of the foreign key and local key
Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method
you can read the laravel relation document
How to check input data in YII2 for REST API?
Here's how it's done in a non-REST API:
Controller
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\Index__GET;
class SiteController extends Controller
{
public function actionIndex($ch_name_url = null)
{
$model = new Index__GET();
$model->ch_name_url = $ch_name_url;
if($model->validate()){
return $this->render('index');
}
}
}
Model
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class Index__GET extends Model
{
public $ch_name_url;
public function rules()
{
return [
['ch_name_url', 'trim'],
['ch_name_url', 'required'],
];
}
}
And now in the controller call $model->validate() for data validation. How to do validation incoming data in the REST API, using yii\rest\Controller and yii\rest\ActiveController?
I try but data validation fails:
I want a GET request to include two required fields.
But if I use /users/123 I will receive data, while I should not receive it, because of the model [['id', 'ch_name_url'], 'required'],.
Me need /users?id=123&ch_name_url=myname
Controller
namespace app\controllers;
use yii\rest\ActiveController;
class IndexController extends ActiveController
{
public $modelClass = 'app\models\Index__GET';
}
Model
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Index__GET extends ActiveRecord
{
public $id;
public $ch_name_url;
public $email;
public static function tableName()
{
return 'user';
}
public function fields()
{
return ['id', 'ch_name_url', 'email'];
}
public function rules()
{
return [
[['id', 'ch_name_url'], 'required'],
];
}
}
Just create a controller extending from \yii\rest\ActiveController, then validate will run automatically. Do something like this:
namespace app\controllers;
use yii\rest\ActiveController;
class IndexController extends ActiveController
{
public $modelClass = 'app\models\Index__GET';
}
$model->validate() is called by default when you call $model->save(), but if you need to validate a model in an action, do it like you did on your question example code.
Just remember that the actions from REST are used a bit different from normal call, where actionIndex usually is not needed.
For more information, follow the original docs: REST Quick Start
I am using couchbase DB in my project. I have a controller and created a Model. My Controller is not recognizing the Model. The code looks like below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Item;
class ItemController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = \DB::connection('couchbase')->table('metis-dev')->get();
}
}
Model Code is below:
namespace App;
//use Illuminate\Database\Eloquent\Model;
use Mpociot\Couchbase\Eloquent\Model as Eloquent;
class Item extends Eloquent
{
//protected $connection = 'couchbase';
protected $table = 'item';
}
protected $guarded = []; use that in your model.
I'm trying to change the $id param in my controller methods on the fly using beforeAction and a behavior. FYI, I'm going to use HashIds and need to convert anywhere I have a $_GET['id'] that may be hashed back into an integer.
How can I use a behavior to automatically modify my $_GET['id'] on the fly using a behavior?
An example action in my controller:
public function actionView($id){
// run code to process $id here back to integer using a behavior
echo $id; //should be an integer
}
My sample url: http://mydomain/posts/view?id=3QhLp
(Alternatively, perhaps the better way to do this is to create a custom url rule?)
you should implement a class that extends from the \yii\base\Behavior like below
<?php
namespace backend\models;
use Yii;
use yii\base\Behavior;
use yii\web\Controller;
class Transformer extends Behavior
{
public $id = '';
public function events()
{
return [Controller::EVENT_BEFORE_ACTION => 'transform']; //mounting the handler to the 'beforeAction' event on the controller.
}
public function transform()
{
$_GET['id'] = $this->id . "transformed"; //mock method here
return true;
}
}
Then in your controller, adding the code as follow:
public function behaviors()
{
return [
'transformer' => [
'class' => \backend\models\Transformer::className(), //Modify the path to your real behavior class.
'id' => Yii::$app->request->get('id'),
],
];
}
then access the Yii::$app->request->get('id') in your action, you will see the transformed url param.
I'm trying to reference the Requests class in Laravel, I've tried so many fixes with the keyword "use" but each time I keep getting Reflection exception
that says app\path\specified doesn't exist. I'm confused.
Here is my code:`
<?php
namespace App\Http\Controllers;
//namespace App\Http\Request;
//use Illuminate\Http\Requests;
//use app\Http\Requests\ContactFormRequest;
use App\Message;
use App\Mail\SendMessage;
use Session;
//use App\Requests;
class AboutController extends Controller
{
public function create()
{
return view ('about.contact');
}
public function store(App\Requests\SendMessageRequest $request)
{
$message = $request->message;
Mail::to('myemail')
->send(new SendMessage($message, $request->email,$request->name));
THE REQUESTS CLASS
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required',
'email' => 'required|email',
"message" => 'required',
];
}
}
The commented line(//) are what I've tried
SendMessageRequest is the name of my Request class.
Sorry, I canĀ“t comment your post. However can you also send the SendMessageRequest Class? Is that a subclass of the Request in Laravel?