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);
Related
In Product model I have:
public function getImage()
{
return $this->hasMany(Image::className(), ['product_id' => 'id']);
}
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image->path;
}
In view file I have ListView with _item file:
<img src="<?=$model->getMainImage()?>"></img>
Controller:
$dataProvider = new ActiveDataProvider([
'query' => Product::find()->with(['image']),
]);
Error is:
Trying to get property 'path' of non-object.
The code you have submitted may cause this error if the image was not found.
You should include a null check.
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image ? $image->path : false;
}
You may also want to look at implementing this with an AR relation via hasOne, which would be more concise. It is documented here:
https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasOne()-detail
Have you write full code:
return is_null($image) ? false : $image->path;
if not working, check your condition!
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();
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']);
}
I am using MySQL as the database connection adapter for all my models. I have a downloads model and controller with an index function that renders either an HTML table or a CSV file depending on the type passed from the request. I also have a CSV media type to handle an array of data, which is working as expected (outputs array keys as headers then array values for each row of data).
I wish to do the same find query but then remove ID fields from the record set if a CSV file is going to be rendered. You'll notice that the download ID is being fetched even though it is not in the fields array, so simply changing the fields array based on the request type will not work.
I have tried the following in the index action of my downloads controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
if ($this->request->params['type'] == 'csv') {
$downloads->each(function ($download) {
// THIS DOES NOT WORK
unset($download->id, $download->user_id);
// I HAVE TRIED THIS HERE AND THE ID FIELDS STILL EXIST
// var_dump($download->data());
// exit;
return $download;
});
return $this->render(array('csv' => $downloads->to('array')));
}
return compact('downloads');
}
}
?>
I thought there was an __unset() magic method on the entity object that would be called when you call the standard PHP unset() function on an entity's field.
It would be great if there was a $recordSet->removeField('field') function, but I can not find one.
Any help would be greatly appreciated.
Perhaps you should do $downloads = $downloads->to('array');, iterate the array with a for loop, remove those fields from each row, then return that array. If you have to do this same thing for a lot of actions, you could setup a custom Media handler that could alter the data without needing logic for it in your controller.
Take a look at this example in the Lithium Media class unit test.
You can also avoid having much logic for it in your controller at all through the use of a custom handler. This example also auto-generates a header row from the keys in your data.
In config/bootstrap/media.php:
Media::type('csv', 'application/csv', array(
'encode' => function($data, $handler, $response) {
$request = $handler['request'];
$privateKeys = null;
if ($request->privateKeys) {
$privateKeys = array_fill_keys($request->privateKeys, true);
}
// assuming your csv data is the first key in
// the template data and the first row keys names
// can be used as headers
$data = current($data);
$row = (array) current($data);
if ($privateKeys) {
$row = array_diff_key($row, $privateKeys);
}
$headers = array_keys($row);
ob_start();
$out = fopen('php://output', 'w');
fputcsv($out, $headers);
foreach ($data as $record) {
if (!is_array($record)) {
$record = (array) $record;
}
if ($privateKeys) {
$record = array_diff_key($record, $privateKeys);
}
fputcsv($out, $record);
}
fclose($out);
return ob_get_clean();
}
));
Your controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
$this->request->privateKeys = array('id', 'user_id');
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
return compact('downloads');
}
}
?>
Why not then just dynamically set your $fields array?
public function index() {
$type = $this->request->params['type'];
//Exclude `user_id` if request type is CSV
$fields = $type == 'csv' ? array('Surveys.name') : array('user_id', 'Surveys.name');
$conditions = array(...);
$with = array('Surveys');
$order = array('created' => 'desc');
$downloads = Downloads::find('all', compact('conditions', 'fields', 'with', 'order'));
//Return different render type if CSV
return $type == 'csv' ? $this->render(array('csv' => $downloads->data())) : compact('downloads');
}
You can see in this example how I send the array for your CSV handler, otherwise it's the $downloads RecordSet object that goes to the view.
I'm setting up pagination to display a list of images belonging to the user in their account. This is what I have in my controller:
class UsersController extends AppController {
public $paginate = array(
'limit' => 5,
'order' => array(
'Image.uploaded' => 'DESC'
)
);
// ...
public function images() {
$this->set('title_for_layout', 'Your images');
$albums = $this->Album->find('all', array(
'conditions' => array('Album.user_id' => $this->Auth->user('id'))
));
$this->set('albums', $albums);
// Grab the users images
$options['userID'] = $this->Auth->user('id');
$images = $this->paginate('Image');
$this->set('images', $images);
}
// ...
}
It works, but before I implemented this pagination I had a custom method in my Image model to grab the users images. Here it is:
public function getImages($options) {
$params = array('conditions' => array());
// Specific user
if (!empty($options['userID'])) {
array_push($params['conditions'], array('Image.user_id' => $options['userID']));
}
// Specific album
if (!empty($options['albumHash'])) {
array_push($params['conditions'], array('Album.hash' => $options['albumHash']));
}
// Order of images
$params['order'] = 'Image.uploaded DESC';
if (!empty($options['order'])) {
$params['order'] = $options['order'];
}
return $this->find('all', $params);
}
Is there a way I can use this getImages() method instead of the default paginate()? The closest thing I can find in the documentation is "Custom Query Pagination" but I don't want to write my own queries, I just want to use the getImages() method. Hopefully I can do that.
Cheers.
Yes.
//controller
$opts['userID'] = $this->Auth->user('id');
$opts['paginate'] = true;
$paginateOpts = $this->Image->getImages($opts);
$this->paginate = $paginateOpts;
$images = $this->paginate('Image');
//model
if(!empty($opts['paginate'])) {
return $params;
} else {
return $this->find('all', $params);
}
Explanation:
Basically, you just add another parameter (I usually just call it "paginate"), and if it's true in the model, instead of passing back the results of the find, you pass back your dynamically created parameters - which you then use to do the paginate in the controller.
This lets you continue to keep all your model/database logic within the model, and just utilize the controller to do the pagination after the model builds all the complicated parameters based on the options you send it.