Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: virtual fields containing model related data fields

I've got a model Employee which belongsTo an Address-model. When I fetch data from the Employees model, the associated Address record gets fetched too. Additionally, the Address model has a virtualField full_name. This looks like this:

Array 
(
[0] => Array
       (
        [Employee] => Array
            (
                [id] => 1
                [address_id] => 33
                [username] => ...
                ...
            )

        [Address] => Array
            (
                [id] => 33
                [firstname] => Blah
                [full_name] => Blah Blubb
                ...
            )

    )

[1] => Array  (
        [Employee] => Array   (
                [id] => 2
                ...

I want to have included this virtualField in the Employee part of the data array too, like

Array (
[0] => Array (
        [Employee] => Array
            (
                [id] => 1
                [full_name] => Blah Blubb
                ...
            )

Tis isn't possible to solve by just adding

$virtualFields = array(
    'full_name' => 'CONCAT_WS(" ", Address.firstname, Address.surname)',
);

to the Employees model, as the Cookbook states There is a solution proposed ("copy virtualFields from one model to another at runtime when you need to access them"), but I don't understand this solution. Where do I have to place this? In the controller? In the model in the find function?

Thanks for Help

like image 553
joni Avatar asked Sep 30 '10 15:09

joni


1 Answers

http://book.cakephp.org/view/1608/Virtual-fields#Virtual-fields-and-model-aliases-1632

The implementation of virtualFields in 1.3 has a few limitations. First you cannot use virtualFields on associated models for conditions, order, or fields arrays. Doing so will generally result in an SQL error as the fields are not replaced by the ORM. This is because it's difficult to estimate the depth at which an associated model might be found.

like image 75
havvg Avatar answered Sep 30 '22 00:09

havvg