how to extract this data in yii2 mysql - php

The data to be extracted are:
->select('ingreso.idingreso', 'ingreso.fecha_hora', 'persona.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado', 'SUM("ingreso.cantidad*precio_cantidad") AS total')
the relationships of the models in the tables:
table "ingreso"
public function relations()
{
return array(
'didingreso' => array(self::HAS_MANY,'detalle_ingreso', 'idingreso'),
);
}
table "detalle_ingreso"
public function relations()
{
return array(
'ingres' => array(self::HAS_ONE,'ingreso', 'idingreso'),
'articulo' => array(self::HAS_ONE,'articulo', 'idarticulo'),
);
}
table "articulo"
public function relations()
{
return array(
'idproveed' => array(self::HAS_MANY,'ingreso', 'idproveedor'),
);
}
table "persona"
public function relations()
{
return array(
'idproveed' => array(self::HAS_MANY,'ingreso', 'idproveedor'),
);
}
without the relationships I tried to do this:
$table = Ingreso::find()
->innerJoinWith('persona', 'ingreso.idproveedor = persona.idpersona')
->innerJoinWith('detalle_ingreso', 'ingreso.idingreso = detalle_ingreso.idingreso')
->select('ingreso.idingreso', 'ingreso.fecha_hora', 'ingreso.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado', 'SUM("detalle_ingreso.cantidad*detalle_ingreso.precio_venta") AS total')
->andWhere(["estado" => 'A'])
->orderBy(['ingreso.idingreso' => SORT_DESC])
->groupBy(['ingreso.idingreso', 'ingreso.fecha_hora', 'ingreso.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado']);
these are my tables:
the error that throws me apparently is when trying to access the result and is the following:
thanks for your help.

If you are using Yii2 you should use the relations statements from yii2 activeRecord.
Here the documentation
EDIT:
You should create all realtions that you need individually and then create a mixed query with with
Your Model:
public function getIngreso(){
return $this->hasMany(Ingreso::className(), ['id' => 'id_ingreso']);
}
public function getDetalleingreso(){
return $this->hasMany(DetalleIngreso::className(), ['id' => 'id_detalleingreso']);
}
In your controller:
$results = $model->find()->select('foo')->with(['ingreso', 'detalleingreso'])->all();

Related

How to output data in multipleSelect to laravel-admin form?

Model - Promo:
...
protected $table = 'promo';
...
public function locations()
{
return $this->belongsToMany(Cities::class, 'cities_promo');
}
Controller in laravel-admin
...
protected function form()
{
$location = Cities::pluck('name', 'id');
$form = new Form(new Promo);
$form->text('title', __('Title'));
$form->textarea('desc', __('Description'));
$form->multipleSelect('locations')->options($location);
return $form;
}
...
The bottom line is that it does not display the values that were previously selected and saved. An empty field is displayed there, where you can select values from the City model.
An intermediate solution was to use the attribute.
It is necessary that the format for multipleSelect (and others) was in array format [1,2,3 ... ,7].
In normal communication, an array of the form is transmitted:
{
['id' => 1,
'name' => 'Moscow',
...
],
['id' => 2,
'name' => 'Ekb',
...
],
}
Therefore, for formalization, I used a third-party attribute "Cities" to the model "Promo".
...
//Add extra attribute
//These attributes will be written to the database, if you do not want
//this, then do not advertise!
//protected $attributes = ['cities'];
//Make it available in the json response
protected $appends = ['cities'];
public function getCitiesAttribute()
{
return $this->locations->pluck('id');
}
public function setCitiesAttribute($value)
{
$this->locations()->sync($value);
}
If there are other suggestions, I am ready to listen.
Thank.
change $location to
$location = Cities::All()->pluck('name', 'id');
you can return $location to know it has value or not
also you can set options manually
$form->multipleSelect('locations')->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);
to know it works

Category isn't getting related video blogs?

I am trying to get category related video blogs by below code but i get nothing in var_dump? I want to get category related videos:
$category = VideoBlogCategoryModel::findFirst(1); // This returns category successfully and there are many video blogs having this category linked
var_dump($category->getVideoBlogs());exit;
VideoBlogModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure Relation with VideoBlogCategoryModel
$this->belongsTo('category_id', VideoBlogCategoryModel::class, 'id', array(
'alias' => 'videoCategory',
'foreignKey' => true
));
}
public function getVideoCategory(){
return $this->videoCategory;
}
public function setVideoCategory($videoCategory){
$this->videoCategory = $videoCategory;
}
VideoBlogCategoryModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure relation with VideoBlogModel
$this->hasMany('id', VideoBlogModel::class, 'category_id', array(
'alias' => 'videoBlogs',
'foreignKey' => true,
'cxAction' => static::ACTION_CASCADE_DELETE
));
}
public function getVideoBlogs(){
return $this->videoBlogs;
}
public function setVideoBlogs($videoBlogs){
$this->videoBlogs = $videoBlogs;
}
Let me know if anything else is required, I will share it.
In VideoBlogCategoryModel.php change
public function getVideoBlogs() {
return $this->videoBlogs;
}
to
public function getVideoBlogs() {
return $this->getRelated('videoBlogs');
}
Then try accessing it like:
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
foreach( $videos as $video ) {
// access data here
var_dump($video->anyProperty()); // e.g $video->getId()
}
can you try it
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
var_dump($videos->count());
var_dump($videos->toArray());
exit;
I think use var_dump for a Phalcon Collection Object is not a good idea, you can convert it to Array and Var_dump
Hope it can help you
Or try:
$categories = VideoBlogCategoryModel::findById($id);

yii get has_many relations count

How to get the count of childCompetency through childDomain which having has many relation
'childDomain' => array(self::HAS_MANY, 'SkillRelDomain', 'skill_id'),
'childCompetency' => array(self::HAS_MANY, 'SkillRelCompetency', 'domain_id'),
Here is a one to many (User:Post) relationship example in Yii 1
In case of post every post belongs to a user. So relation looks like this.
public function relations() {
return array(
'user'=>array(self::BELONGS_TO, 'User', 'iduser'),
);
}
Similarly, a user can have multiple posts. So relation for user as:
public function relations() {
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'iduser'),
);
}
Now when you do a $user = User::model()->findByPk($id), you can have access to relation data also
you can call
foreach($user->posts as $post){
echo $post->name;
}

Modify data before pagination in CakePhp

I'm trying to create an Api using cakephp.
I generate a json on server and it works fine , but I tired to use pagination and I got a problem.
in the first case I take the image's path and I encode it to base64 and I generate json => works
in the second case I defined the pagination by the limits and the max and I kept the same code but as a result the image field is still the path from the database and it's not encoded
this my code in my controller :
class PilotsController extends AppController {
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 5
];
public function initialize() {
parent::initialize();
$this->loadComponent('Paginator');
$this->Auth->allow(['add','edit','delete','view','count']);
}
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $this->paginate($pilot));
$this->set('_serialize', ['pilot']);
}
}
If I remove the pagination from the code it works fine . Any idea how to fix it ??
I'd suggest to use a result formatter instead, ie Query::formatResults().
So you'll have something like this :
public function view($id) {
$pilot = $this->Pilots->find()
->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']]);
->formatResults(function($results) {
return $results->map(function($row) {
$image1 = file_get_contents(WWW_ROOT.$row['image_pilot']);
$row['image_pilot'] = base64_encode($image1);
return $row;
});
});
}
You can simply first paginate the data and then get the array values and after that modify that data as you want. Check this
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
$pilot = $this->paginate($pilot);
$pilot = $pilot->toArray();
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $pilot);
$this->set('_serialize', ['pilot']);
}

Yii CActiveDataProvider MANY::MANY

i got 2 models: Project and Users connected with (User.php):
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
"projects"=>array(self::MANY_MANY, 'Project','projects_users(user_id, project_id)'),
);
}
I want to show all users in CActiveDataProvider who are not connected with project. How can i do it?
I found solution:
$criteria=new CDbCriteria;
foreach($model->users as $cur) {
$criteria->addCondition("ID != ".$cur->ID);
}
$users=User::model()->findAll($criteria);
$dataProvider2=new CActiveDataProvider('User');
$dataProvider2->data = $users;
Try this:
$users = User::model()->with('projects')->findAll(array(
'together' => true,
'condition' => 'projects.id IS NULL',
));

Categories