Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Model relations

Hey guys, I need our help.

I have 2 database tables - categoriesand categories_description.

CREATE TABLE `categories` (
  `id` int(11) NOT NULL,
  `route` int(3) NOT NULL,
  `sort_order` int(3) NOT NULL DEFAULT '0',
  `active` char(1) NOT NULL DEFAULT 'Y', 
  `createAt` datetime NOT NULL,
  `updateAt` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `categories_description` (
  `id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `language_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
class Categories extends \Phalcon\Mvc\Model
{
    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->hasOne('id', __NAMESPACE__ . '\CategoriesDescription', 'category_id', [
            'alias'      => 'description',
            'foreignKey' => [
                'action' => Model\Relation::ACTION_CASCADE
            ]
        ]);
    }
}
class CategoriesDescription extends \Phalcon\Mvc\Model
{
    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->belongsTo('category_id', __NAMESPACE__ . '\Categories', 'id', [
            'alias' => 'categories'
        ]);
    }
}

So far so good.

// category with id=1
$category = Categories::find(1);

// give all descriptions
$descriptions = $category->description;

// description with language_id=5 from category
$description = $category->???;

How do I get the data of one language, e.g: language_id=5?



34.1k
Accepted
answer

The $descriptions is a collection of data so you will have to iterate through them to find which element has $language_id = 5

Alternatively you can do this

$language = $category->getRelated(
    'description`,
    [
        'language_id = 5'
    ]
);


258

Great thx, Nikolaos. Works fine !