CakePHP virtual field: replace one string with another - mysql

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.

Related

Laravel: How to get counter value when inserting with UUID and Auto Increment

My models have both id and counter attributes. The id is a UUID, and the counter is an integer which is auto-incremented by the database.
Both are unique however I rely on id as the primary key. The counter is just a human-friendly name that I sometimes display to the user.
Immediately before an object is created a listener gives it a UUID. This works fine.
When the record is saved, MySQL increments the counter field. This works fine except that the copy of the object which I have in memory does not have the counter value. I can reload the object to find out what its counter is, but that would require another database query.
Is there a way to find the value of the counter without a specific database query? For example, is it returned as part of the response from the database when a record is created?
Few things:
Use create(array $attributes) and you'll get exactly what you want. For this having right, you have to ensure that $fillable array consists all attributes' names passed to create method.
You should use Observer on model instead of listener (most likely creating method).
Personal preference using Eloquent is that you should use id for id (increment field) and forget custom settings between models because by default it is what relations expect and so on
public function secondModels()
{
return $this->hasMany(SecondModel::class);
}
is pretty much no brainer. But for having this working best way would be (also following recommendations of this guy) FirstModel::id, SecondModel::id, SecondModel::first_model_id; first_models, second_models as table names. Avoiding and/or skipping this kind of unification is lot of custom job afterward. I don't say it can't be done but it is lot of non-first-time-successful work done.
Also, if you want visitor to get something other than id field name, you can make computed field with accessor:
/**
* Get the user's counter.
*
* #return string
*/
public function getCounterAttribute(): string
{
return (string)$this->id;
}
Which you call then with $user->counter.
Also personal preference of mine is to have most possible descriptive variable names so uuid field of mine would be something like
$table->uuid('uuid4');
This is some good and easy to make practice of Eloquent use.
Saying all this let me just to say that create() and save() will return created object from database while insert() shall not do it.

How select a single row october cms

How to select a single row on october cms?
How can a simple thing be so complicated here?
I thought it would be something to help us and not to disturb something that is as simple as
SELECT * FROM `engegraph_forms_membros`
Here it's like fighting against demons without a bible, oh god why?
Why make the query difficult for newbie?
I understand you don't speak English natively but you should watch every single one of these videos.
Does the record belong to a model in a plugin? Here are the docs on how to work with models.
You make a plugin, set the database which creates models, and then make components to be ran in your CMS Pages.
In a component.php file you can have something like this: Here I am calling the model class Agreements with use Author\Plugin\Models\Agreements;. This allows me to run a function/method to retrieve all agreements or one agreements using laravel's eloquent collection services.
Lets say we have the ID of a record. Well we can either call on the Agreements model with ::find or with ::where. You will noticed I have two functions that essentially do the same thing. ::find uses the primary key of the models (in my case the id) and will return a singular record. *Note that find can take an array and return a collection of records; like ::where. Using ::where we are going to look for the ID. *Note ::where always returns a collection which is why I have included ->first().
<?php namespace Author\Plugin\Components;
use Session;
use Input;
use Crypt;
use Db;
use Redirect;
use Illuminate\Contracts\Encryption\DecryptException;
use October\Rain\Support\Collection;
use Author\Plugin\Models\Agreements;
class GetAgreement extends \Cms\Classes\ComponentBase
{
public function componentDetails()
{
return [
'name' => 'Get one agreement',
'description' => 'Get an agreement to change or delete it'
];
}
public function onRun() {
$this->page['agreement'] = $this->getWithFindAgreement;
}
public function getWithFindAgreement() {
$id = 1;
$agreement = Agreements::find($id);
return $agreement;
}
public function getWithWhereAgreement() {
$id = 1;
$agreement = Agreements::where($id)->first();
return $agreement;
}
}
If for some reason you aren't working with models, here are the docs to work with Databases. You will have to register the use Db; facade.
Here call the table you want and use ::where to query it. *Note the use of ->first() again.
$users = Db::table('users')->get();
$user = $users->where('id', 1)->first();
There are two simple ways to select a single row:
This will give you the'first' record in the selected recordset.
SELECT top 1 * FROM `engegraph_forms_membros`
This will select all the records that meet the predicate requirement that the value of <columnname> is equal to <value>
SELECT * FROM `engegraph_forms_membros` where <columnname>=<value>
If you select a record where multiple values meet that requirement, then you can (randomly) pick one by combining the solutions...
SELECT top 1 * FROM `engegraph_forms_membros` where <columnname>=<value>
But be aware that without an ORDER BY clause, the underlying data is unordered and prone to change uncontrollably, which is why most people (including your boss) will find the use of 'Top' to be improper for real use.

Yii - using MySQL AS clause field

Let's say I want to have a provide CActiveDataProvider for a CGridView. I need to put a SUM(invitesCount) AS invites into a Provider result. How to retrieve it? I guess I cannot just use $dataProvider->invites?
You need to specify the following in your relationinvites
'invites '=>array(self::BELONGS_TO, 'CampaignFund', 'campaign_id', 'select' => 'SUM(invitesCount)'),
and use this relation in your criteria.
Several other options:
Use CStatRelation
invitesCount=>array(self::STAT,'Invites','foreign_key_field');
The addition of a public property can work. However, the field would only be set if you altered the default find query to include this new condition. This can be done by overriding defaultScope() or creating a new scope and using it whenever invitesCount is required.
Another option would be to create a database view from the required query and create a new Model from that database view.

Doctrine complex entities

Let's say i have two Doctrine entities:
Users and Messages
Every user can have 'n' messages.
Now I want to display the mailbox for a user so I fetch the user entity from the ORM and from this entity I get all messages. No problem so far.
But now i want to have some more complexe filtering of the messages. For example: Max age, Max count, blacklisting some words etc. So the default getter method of the entity for getting the messages isn't enough.
How can i solve this?
A entity repository is the first thing i found but then i have to ask this repoitory from outside of the user object which breaks the relationship of user and message (repository->getMessagesForUser(userId,...) instead of user->getMessages(...)) which doesn't look like a 'clean' OOP solution for me.
Another way i could think of is to ignore all this fancy ORM stuff and write my own models and getting the informations from the database on the lowest ORM or even DBAL layer. And ether wrap the entity or fill the fields of my own models manually. But then i ask myself: "Why did i use Doctrine?".
So what's the best practice for this case. By the way i use Symfony 2.
In this specific case, I would definitely make the Message its own aggregate, and therefore would create a Repository for it, and remove the relationship from User to Message. The User can have many Messages anyway, so it would be very inefficient to use the other approach.
I would then create specific methods in the MessageRepository:
class MessageRepository
{
public function findByUser(User $user) {
// ...
}
public function findReadMessagesByUser(User $user) {
// ...
}
}

Last inserted id in cakephp

I use this code but its not working in cakephp and the code is:
$inserted = $this->get_live->query("INSERT INTO myaccounts (fname) values('test');
After this im using:
$lead_id = $this->get_live->query("SELECT LAST_INSERT_ID()");
It's working, but only one time.
Try this. Lots less typing. In your controller, saving data to your database is as simple as:
public function add() {
$data = "test";
$this->Myaccount->save($data);
// $this->set sends controller variables to the view
$this->set("last", $this->Myaccount->getLastInsertId());
}
You could loop through an array of data to save with foreach, returning the insertId after each, or you could use Cake's saveAll() method.
Myaccount is the Model object associated with your controller. Cake's naming convention requires a table called "myaccounts" to have a model class called "Myaccount" and a controller called "Myaccounts_Controller". The view files will live in /app/views/myaccounts/... and will be named after your controller methods. So, if you have a function add()... method in your controller, your view would be /app/Views/Myaccounts/add.ctp.
The save() method generates the INSERT statement. If the data you want to save is located in $this->data, you can skip passing an argument in; it will save $this->data by default. save() even automagically detects whether to generate an UPDATE or an INSERT statement based on the presence of an id in your data.
As a rule of thumb, if you're using raw sql queries at any point in Cake, you're probably doing it wrong. I've yet to run into a query so monstrously complex that Cake's ORM couldn't model it.
http://book.cakephp.org/2.0/en/models/saving-your-data.html
http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html?highlight=getlastinsertid
HTH :)
You can get last inserted record id by (works for cakePHP 1.3.x and cakePHP 2.x)
echo $this->ModelName->getLastInsertID();
Alternately, you can use:
echo $this->ModelName->getInsertID();
CakePHP 1.3.x found in cake/libs/model/model.php on line 2775
CakePHP 2.x found in lib/Cake/Model/Model.php on line 3167
Note: This function doesn't work if you run the insert query manually
pr($this->Model->save($data));
id => '1'
id is a last inserted value