简体   繁体   中英

CakePHP virtual field: replace one string with another

I wonder if there is any way to declare a virtual field in CakePHP to do the following: We have to replace a user's status with a symbol and append to it the user's nickname. For example, if a user is an admin, we want to display: @barth , for a regular user ~barth .

I already wrote an afterFind() callback to perform this task, but it fails using the containable behavior.

Either is there another way to implement it, or we can create a virtual field. The latter solution would be very elegant, but after googling I cannot find any way to use MySQL syntax to replace one string with another.

Ideas?

Virtual fields are very easy to use in Cake. You can use any regular MySQL function in their declaration to achieve this type of thing.

You'll first need to determine the SQL command to achieve what you want, I'd suggest using the CONCAT() function:

-- Return an @ concatenated onto the username
CONCAT('@', yourfield)

Then add this as a virtual field in your model:

class YourModel extends AppModel {
    public $virtualFields = array(
        'yourVirtualField' => 'CONCAT("@", yourfield)'
    );
}

Now, when you query this model you should be able to access it like this:

$example = $this->YourModel->find('first');
echo $example['YourModel']['yourVirtualField']; // @yourfield

Edit

Since your update, you've got the values you want to concatenate together in another model as virtual fields already. CakePHP doesn't allow you to use associated models' virtual fields when creating a new virtual field , but you can do a subselect query to manually get this data. Here's an SQL Fiddle example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM