yii detecting if scope is in use - yii

I was wondering if there's a method to detect if a scope is being used on an AR search in yii?
For example, a model might contain 2 scopes:
class MyModel extends CActiveRecord
{
...
function myScope1()
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo = bar',
));
return $this;
}
function myScope2()
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo2 = bar2',
));
return $this;
}
....
}
I'm calling the AR like so:
$results = MyModel::model()->myScope1()->myScope2()->findAll();
It's a very dynamic site and there are more than 2 scopes, some used, some not. there are a couple of scopes that shouldn't be applied if another scope is in use. To avoid hundreds of if else statements, can I do something like so:
class MyModel extends CActiveRecord
{
...
function myScope1()
{
$this->getDbCriteria()->mergeWith(array(
'condition'=>'foo = bar',
));
return $this;
}
function myScope2()
{
if($this->appliedScopes('myScope1')==false)
{
// scope myScope1 isn't applied, so apply this scope:
$this->getDbCriteria()->mergeWith(array(
'condition'=>'foo2 = bar2',
));
}
return $this;
}
....
}

Typical, think of a workaround almost right after posting!
In my case, applying 'OR' between the two scopes will work, so;
class MyModel extends CActiveRecord
{
...
function myScope1()
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo = bar',
));
return $this;
}
function myScope2($useAnd=true)
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo2 = bar2',
),$useAnd);
return $this;
}
....
}
Calling like so:
$results = MyModel::model()->myScope1()->myScope2(false)->findAll();

Related

Flatten laravel nested relationship (parent to descendants) get all childerns

This is my Controller
$categoryIds = Category::select('id')->with('childrenRecursive')->where('id', 1)->get();
Ad::whereIn('category_id', $categoryIds)->get();
This is my model
public function parent() {
return $this->belongsTo(Category::class, 'parent_id');
}
public function childs() {
return $this->hasMany(Category::class, 'parent_id');
}
public function Ads() {
return $this->hasManyThrough(Ad::class, Category::class, 'parent_id', 'category_id', 'id');
}
How get all childern categories ides
I solved this problem with this solution
My Controller
public function index()
{
$parent = Category::with('descendants')->find(1);
$descendants = $this->traverseTree($parent, collect([1]));
$ads = Ad::whereIn('category_id',$descendants)->get();
return response($ads);
}
protected function traverseTree($subtree, $des)
{
$descendants = $des;
if ($subtree->descendants->count() > 0) {
foreach ($subtree->descendants as $descendant) {
$descendants->push($descendant);
$this->traverseTree($descendant, $descendants);
}
}
return $descendants;
}
I'd do it with Laravel's Subqueries approach.
$parentId = 4;
Ad::whereIn('category_id', function($q) use ($parentId) {
$q->select('id')
->from('categories')
->where('parent_id', $parentId);
});
If you want to add the parent model, you can chain with():
Ads::whereIn('category_id', function($q) use ($parentId) {
$q->select('id')
->from('categories')
->where('parent_id', $parentId);
})
->with('category.parent')
->get();
Your code chunks are not clear so you may need to tweak my code example.
If I understand your question properly you need to get ads corresponding to id's of all related records also, for a given category record.
$category = Category::with('childs:id,parent_id')
->where('id', 1)
->firstOrFail();
$categoryIds = collect([$category->parent_id, $category->id]);
$category->childs->map(fn($child) => $categoryIds->push($child->id));
$ads = Ads::whereIn('category_id', $categoryIds->filter()->all())
// Can eager load the product(s) if needed
//->with('products')
->get();

I have defined relatioships in models but how can i write complex queries in Eloquent way

I have a query in existing application now i need to update query in eloquent way i have the following structure of my relationships how can i write the following query in eloquent way
Controller Query that i want to change in eloquent way
foreach ($data['Divisions'] as $sections) {
$SecQry1 = "SELECT sections.id, sections.division_id, sections.code, sections.name ,specifications.description
from specifications inner JOIN sections on specifications.section_id=sections.id where specifications.status='active'
AND specifications.manufacturer_id = $user->id AND sections.division_id=" . $sections->id . " group by sections.id";
$SectionsDivision1 = DB::select($SecQry1);
foreach ($SectionsDivision1 as $key => $selectionDiv) {
array_push($selectionDiv_array1, $selectionDiv);
}
}
class Specification extends Model {
protected $table = 'specifications';
public function section()
{
return $this->belongsTo('App\Section');
}
}
class Section extends Model {
protected $table = 'sections';
public function specifications()
{
return $this->hasMany('App\Specification', 'section_id');
}
public function division()
{
return $this->belongsTo('App\Division');
}
}
class Division extends Model {
protected $table = 'divisions';
protected $fillable = array('name', 'description', 'code','status');
public function sections()
{
return $this->hasMany('App\Section', 'division_id');
}
}
0 => {#1063 ▼
+"id": 1
+"division_id": 1
+"code": "03 01 00"
+"name": "Maintenance of Concrete"
+"description": null
}
]
You dont need relations for this specific query, you could use Laravel Eloquent with join like so:
$SectionsDivision1 = Specification::join('sections', 'specifications.section_id', '=', 'sections.id')
->where([
'specifications.status' => 'active',
'specifications.manufacturer_id' => $user->id,
'sections.division_id' => $sections->id
])->select('sections.id', 'sections.division_id', 'sections.code', 'sections.name', 'specifications.description')
->groupBy('sections.id');
I hope it helps

How to validate two dimensional array in Yii2

How to validate two dimensional array in Yii2.
passenger[0][name] = bell
passenger[0][email] = myemail#test.com
passenger[1][name] = carson123
passenger[1][email] = carson###test.com
how to validate the name and email in this array
Thanks
Probably the most clean solution for validating 2-dimensional array is treating this as array of models. So each array with set of email and name data should be validated separately.
class Passenger extends ActiveRecord {
public function rules() {
return [
[['email', 'name'], 'required'],
[['email'], 'email'],
];
}
}
class PassengersForm extends Model {
/**
* #var Passenger[]
*/
private $passengersModels = [];
public function loadPassengersData($passengersData) {
$this->passengersModels = [];
foreach ($passengersData as $passengerData) {
$model = new Passenger();
$model->setAttributes($passengerData);
$this->passengersModels[] = $model;
}
return !empty($this->passengers);
}
public function validatePassengers() {
foreach ($this->passengersModels as $passenger) {
if (!$passenger->validate()) {
$this->addErrors($passenger->getErrors());
return false;
}
}
return true;
}
}
And in controller:
$model = new PassengersForm();
$model->loadPassengersData(\Yii::$app->request->post('passenger', []));
$isValid = $model->validatePassengers();
You may also use DynamicModel instead of creating Passanger model if you're using it only for validation.
Alternatively you could just create your own validator and use it for each element of array:
public function rules() {
return [
[['passengers'], 'each', 'rule' => [PassengerDataValidator::class]],
];
}
You may also want to read Collecting tabular input section in guide (unfortunately it is still incomplete).

Extended CRUD, function formSubmit don't get all form elements?

i have a problem, i cannot get values (added with $form->addField) from form in CRUD. I just get what's in the model, but there just isn't extra values...
MODEL:
class Model_Admin extends Model_Table {
public $table ='admin';
function init(){
parent::init();
$this->addField('name')->mandatory('Name required');
$this->addField('email')->mandatory('Email required');
$this->addField('password')->type('password')->mandatory('Password required');
}
}
On page i create extended CRUD and add two more fields:
$adminCRUD = $this->add('MyCRUD');
$adminCRUD->setModel('Admin');
if($adminCRUD->isEditing('add')){
$adminCRUD->form->addField('line','test2','TEST LINE');
$adminCRUD->form->addField('DropDown', 'appfield','Manages Applications')
->setAttr('multiple')
->setModel('Application');
}
Extended CRUD:
class MyRUD extends CRUD {
function formSubmit($form)
{
//var_dump($form);
var_dump($form->get('test2'));
var_dump($form->get('appfield'));
try {
//$form->update();
$self = $this;
$this->api->addHook('pre-render', function () use ($self) {
$self->formSubmitSuccess()->execute();
});
} catch (Exception_ValidityCheck $e) {
$form->displayError($e->getField(), $e->getMessage());
}
}
}
I get null for $form->get('test2') or $form->get('appfield'). I checked whole $form object and there isn't values from test2.. Somwhere in the process gets lost (or droped), how to get it in extended CRUD?
Thanks in advance!

Zend Framework 2 - Service method require as parameter InputFilter

I have a bit OOD question.
I have service:
namespace Front\Service\Course;
use Front\ORM\EntityManagerAwareInterface;
use Zend\Http\Request;
use Zend\InputFilter\InputFilter;
use Front\InputFilter\Course\CreateFilter;
class Create implements EntityManagerAwareInterface
{
/**
* #var \Doctrine\Orm\EntityManager
*/
protected $entityManager = null;
public function create(CreateFilter $createFilter)
{
if (!$createFilter->isValid()) return false;
/* #var $courseRepository \Front\Repositories\CourseRepository */
$courseRepository = $this->getEntityManager()->getRepository('Front\Entities\Course');
$course = $courseRepository->findByName($createFilter->getCourse());
}
/* (non-PHPdoc)
* #see \Front\ORM\EntityManagerAwareInterface::getEntityManager()
*/
public function getEntityManager()
{
return $this->entityManager;
}
/* (non-PHPdoc)
* #see \Front\ORM\EntityManagerAwareInterface::setEntityManager()
*/
public function setEntityManager(\Doctrine\ORM\EntityManager $entityManager)
{
$this->entityManager = $entityManager;
return $this;
}
}
And controller :
class CreateController extends \Zend\Mvc\Controller\AbstractController
{
public function onDispatch(MvcEvent $e)
{
$jsonModel = new JsonModel();
/* #var $courseCreateService \Front\Service\Course\Create */
$courseCreateService = $this->getServiceLocator()->get('Front\Service\Course\Create');
$courseCreateFilter = new CreateFilter();
$courseCreateFilter->setData($this->params()->fromPost());
if (!$courseCreateFilter->isValid()) {
$jsonModel->setVariable('status', 0);
$jsonModel->setVariable('message', $courseCreateFilter->getMessages());
return;
}
$courseCreateService->create($courseCreateFilter);
}
}
By service method declaration :
public function create(CreateFilter $createFilter)
i force user of the Service to use CreateFilter container which derived from Zend/InputFilter every time when he want to create new Course.
My question is: Might it be better when i will send to the service layer not the Typed object but simple value?
On example in my case it is might looks like:
public function create($courseName)
My CreateFilter looks like:
class CreateFilter extends InputFilter
{
public function __construct()
{
$input = new Input('name');
$validatorChain = new ValidatorChain();
$validatorChain->addValidator(new StringLength(array('max'=>60)))
->addValidator(new NotEmpty());
$input->setRequired(true)->setValidatorChain($validatorChain);
$this->add($input);
}
/**
* #return string | null
*/
public function getCourse()
{
return $this->getValue('name');
}
}
If you provide a concrete class name as you're doing now, you're forever tied to a concrete implementation of the class or one derived from it. If you decide later that you want to use a different class entirely, you have to refactor your service class code, whereas with an interface, you only need to implement it in your new class and your service will continue to work without any changes.
Without any interface at all, your service class would have to do extra checks to first see if it's an object and then if it implements the method you're expecting before it can even begin doing its job. By requiring an interface you remove the uncertainty, and negate the need for checks.
By providing an interface you create a contract between your methods and the classes they're expecting as arguments without restricting which classes may enter into the contract. All in all, contract by interface is preferable to contract by class name, but both are preferable to no contract at all.
I usually bind my entities to my form, so they are populated with the data from the form. This way, you inject the entity to your service and imho that's much cleaner. The service should not be aware of how you got your data.
My "admin" controller for an entity Bar usually is injected with three objects: the repository (to query objects), the service (to persist/update/delete objects) and the form (to modify objects for the user). A standard controller is then very CRUD based and only pushes entities to the service layer:
<?php
namespace Foo\Controller;
use Foo\Repository\Bar as Repository;
use Foo\Form\Bar as Form;
use Foo\Service\Bar as Service;
use Foo\Entity\Bar as Entity;
use Foo\Options\ModuleOptions;
use Zend\Mvc\Controller\AbstractActionController;
class BarController extends AbstractActionController
{
/**
* #var Repository
*/
protected $repository;
/**
* #var Service
*/
protected $service;
/**
* #var Form
*/
protected $form;
/**
* #var ModuleOptions
*/
protected $options;
public function __construct(Repository $repository, Service $service, Form $form, ModuleOptions $options = null)
{
$this->repository = $repository;
$this->service = $service;
$this->form = $form;
if (null !== $options) {
$this->options = $options;
}
}
public function getService()
{
return $this->service;
}
public function getRepository()
{
return $this->repository;
}
public function getForm()
{
return $this->form;
}
public function getOptions()
{
if (null === $this->options) {
$this->options = new ModuleOptions;
}
return $this->options;
}
public function indexAction()
{
$bars = $this->getRepository()->findAll();
return array(
'bars' => $bars,
);
}
public function viewAction()
{
$bar = $this->getBar();
return array(
'bar' => $bar,
);
}
public function createAction()
{
$bar = $this->getBar(true);
$form = $this->getForm();
$form->bind($bar);
if ($this->getRequest()->isPost()) {
$data = $this->getRequest()->getPost();
$form->setData($data);
if ($form->isValid()) {
// Bar is populated with form data
$this->getService()->create($bar);
return $this->redirect()->toRoute('bar/view', array(
'bar' => $bar->getId(),
));
}
}
return array(
'form' => $form,
);
}
public function updateAction()
{
$bar = $this->getBar();
$form = $this->getForm();
$form->bind($bar);
if ($this->getRequest()->isPost()) {
$data = $this->getRequest()->getPost();
$form->setData($data);
if ($form->isValid()) {
$this->getService()->update($bar);
return $this->redirect()->toRoute('bar/view', array(
'bar' => $bar->getId(),
));
}
}
return array(
'bar' => $bar,
'form' => $form,
);
}
public function deleteAction()
{
if (!$this->getRequest()->isPost()) {
$this->getRequest()->setStatusCode(404);
return;
}
$bar = $this->getBar();
$this->getService()->delete($bar);
return $this->redirect()->toRoute('bar');
}
protected function getBar($create = false)
{
if (true === $create) {
$bar = new Entity;
return $bar;
}
$id = $this->params('bar');
$bar = $this->getRepository()->find($id);
if (null === $bar) {
throw new Exception\BarNotFoundException(sprintf(
'Bar with id "%s" not found', $id
));
}
return $bar;
}
}
I made a gist file on Github with this full code (it's better readable) and the service. The service relies on the interface, so you can even swap out the entity object by another one having the same interface.
Check the full thing out here: https://gist.github.com/juriansluiman/5472787
Thanks all for answering, owing to answers and analyzing, i have reached conclusion which most applicable for my situation. I agree that Service in my case should not wait concrete object, it is should wait an abstraction with getCourse method.
And i completely agree with "Crisp" answer:
All in all, contract by interface is preferable to contract by class name, but both are preferable to no contract at all.
So i need to extract Interface with one method
getCourse
or
getName
, and remove
if (!$createFilter->isValid()) return false;
so Interface:
interface CourseInterface
{
/**
* #return String
**/
public function getName();
}
and Service:
class Create implements EntityManagerAwareInterface
{
/**
* #var \Doctrine\Orm\EntityManager
*/
protected $entityManager = null;
/**
* #param CourseInterface $course
* #param UserInterface $creator
*/
public function create(CourseInterface $course)
{
$courseEntity = new Course();
$courseEntity->setName($course->getName());
$this->entityManager->persist($courseEntity);
$this->entityManager->flush();
.....
Thanks all.