Name of associative model in CakePHP - php

At first sorry for my English.
I've got a problem in associative models in CakePHP. When I bind more than two models, for example
$this->Album->bindModel(
array(
'hasMany'=>array(
'Photo'=>array(
'className'=>'Photo'
),
'Album'=>array(
'className'=>'Album'
)
)
)
);
I have:
Array
(
[Album] => Array
(
[id] => 22
[f_name] => Some album
[0] => Array
(
[id] => 19
[f_name] => Another album
[id_parent] => 22
[Photo] => Array
(
....
Is it any way to set a key in parent table? I mean I don't want to have "0" as a key, there can be "Album1", "Album2" and so on.

The problem likely stems from binding a model to itself under the same name. Album hasMany Album probably trips up Cake somewhere. Use a unique name for the association, like Album hasMany SubAlbum.

Related

Laravel keyBy - Sorting results from linked table

I have a BlogPost model that has a belongsToMany relationship called images, this relationship uses a link table to associate the blog post id with the image id.
When pulling in the data for a blog post, the images property looks like this:
[images] => Array
(
[0] => Array
(
[id] => 8304
[original] => /img/blog/2017/5/wifiradio_original_59089cae673db.png
[large] => /img/blog/2017/5/wifiradio_large_59089cae673db.jpg
[medium] => /img/blog/2017/5/wifiradio_medium_59089cae673db.jpg
[small] => /img/blog/2017/5/wifiradio_small_59089cae673db.jpg
[name] => wifiradio.png
[alt] => wifiradio.png
[created_at] => 2017-05-02 14:50:22
[updated_at] => 2017-05-02 14:50:22
[pivot] => Array
(
[blog_post_id] => 47749
[image_id] => 8304
[id] => 136949
[type] => featured
)
)
)
)
The array key is not useful as the numeric value, i would like the array key to be the value of pivot->type.
Laravels keyBy method almost does what I need but I can not get it to work directly on the data returned.
Is it possible to use keyBy from within the model so that data is always returned in a useable format?
I solved this by formatting the array within the controller.
Here's the function I created if anyone has a similair problem:
public function formatPosts($posts){
foreach($posts as $post){
$images = collect($post->images);
unset($post->images);
$post->images = $images->keyBy('pivot.type');
}
return $posts;
}

trying to get a multi table sql query into one result array

I have four tables: followers, users, mixes, songs I am trying to get all the mixes from all the followers of one user, I have that part figured out, but I also want to get the songs from each of those mixes, currently my query is giving me results but each result is for one song on the mix, rather than an array of songs within each result for one mix ... any help would be amazing, my sql skills aren't the greatest and I have spent a lot of time trying to figure this out!
my current query is:
SELECT followers.following_id, users.id, users.user_username, mixes.id, mixes.mix_created_date, mixes.mix_name,songs.song_artist
FROM followers, users, mixes,songs
WHERE followers.user_id = 46
AND users.id = followers.following_id
AND mixes.user_id = followers.following_id
AND mixes.id > 0
ORDER BY mixes.mix_created_date DESC
LIMIT 10
the current result is (from running this through a cakephp custom query)
Array
(
[0] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[song_artist] => Yo La Tengo
)
)
[1] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[song_artist] => Animal Collective
)
)
as you can see the mix id's are the same, I am trying to get the songs to be an array inside of each result like :
Array
(
[0] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[0]=>array(
['song_artist'] => Yo La Tengo
),
[1]=>array(
['song_artist'] => Animal Collective
)
)
)
Really hoping this can be done with just one sql statement! thanks in advance!
You can use the SQL join command to make multiple queries together..
Use this...
sql_join
first a note: it looks like you have a missing condition. according to the above query, every song in songs table will be joined with every result possible. probably there should be a condition similar to the following added: (column names can be different based on your tables):
...
and mix.song_id=songs.song_id
...
as for your question: I don't know php so i regard mysql alone: I don't think it is possible to do it with mysql. mysql returns rows in the result set and each row can contain a single value in each column. to add a group of values (song names) in one column, they must be concatenated (and that is possible: Can I concatenate multiple MySQL rows into one field?), and later you split them back in your php script. this is not a good idea as you will need to choose a separator that you know will never appear in the values that are concatenated. therefore I think its better to remove the songs table from the query and after getting the mix id, run a second query to get all songs in that mix.

User's ID doesn't match user_id in cakephp

I have a table named user. The id is generated on the fly.
I have a HABTM table. I am trying to insert a record during the user registration. For some reason I can't get the user's id and the user_id to match.
This looks correct, even my array reflects the right information, but the actual data stored is not right.
code:
$this->request->data['User']['id'] = String::uuid();
$this->request->data['Company']['Company'][0]['user_id'] = $this->request->data['User']['id'];
returned array:
Array
(
[User] => Array
(
[email_address] => asdf#asdf.com
[id] => 4fc9a939-3e24-4c79-85d1-6c28e4ca782d
)
[Company] => Array
(
[Company] => Array
(
[0] => Array
(
[id] => 4fc9a939-1840-4c1b-8bd2-6c28e4ca782d
[company_id] => 4fc990dd-edb0-4559-bb7b-6a00e4ca782d
[user_id] => 4fc9a939-3e24-4c79-85d1-6c28e4ca782d
)
)
)
)
So it appears that it would work based on the array I got, but it doesn't save like that. Help is much appreciated.
Maybe because cake autogenerates id to UUID (when field is string and length is 36) take a look at CakePHP API - Model->save()

Return values by Yii db

I have a following return value from Yii framework query, using the methods and classes built in Yii:
Array
(
[0] => Array
(
[id] => 1
[title] => Developer
)
[1] => Array
(
[id] => 2
[title] => Tester
)
)
I would like to (using nothing but Yii), rearange this like:
Array
(
[1] => Developer
[2] => Tester
)
Meaning, I will not group the results in a specific index of the array, and I will enlist them all in one array, AND my key/indexes will represent the value of ID field from my table, and value of those keys will be values from my "role" field from my table.
Is this possible and how?
You can use the following method, defined here:
CHtml::listData($yourArray, 'id', 'title');

cakephp - sorting by a second level association in paginate

I am playing around with a quotes database relating to a ski trip I run. I am trying to list the quotes, but sort by the person who said the quote, and am struggling to get the paginate helper to let me do this.
I have four relevant tables.
quotes, trips, people and attendances. Attendances is essentially a join table for people and trips.
Relationships are as follows;
Attendance belongsTo Person hasMany Attendance
Attendance belongsTo Trip hasMany Attendance
Attendance hasMany Quote belongs to Attendance
In the QuotesController I use containable to retrieve the fields from Quote, along with the associated Attendance, and the fields from the Trip and Person associated with that Attendance.
function index() {
$this->Quote->recursive = 0;
$this->paginate['Quote'] = array(
'contain' => array('Attendance.Person', 'Attendance.Trip'));
$this->set('quotes', $this->paginate());
}
This seems to work fine, and in the view, I can echo out
foreach ($quotes as $quote) {
echo $quote['Attendance']['Person']['first_name'];
}
without any problem.
What I cannot get to work is accessing/using the same variable as a sort field in paginate
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
or
echo $this->Paginator->sort('Location', 'Attendance.Trip.location');
Does not work. It appears to sort by something, but I'm not sure what.
The $quotes array I am passing looks like this;
Array
(
[0] => Array
(
[Quote] => Array
(
[id] => 1
[attendance_id] => 15
[quote_text] => Hello
)
[Attendance] => Array
(
[id] => 15
[person_id] => 2
[trip_id] => 7
[Person] => Array
(
[id] => 2
[first_name] => John
[last_name] => Smith
)
[Trip] => Array
(
[id] => 7
[location] => La Plagne
[year] => 2000
[modified] =>
)
)
)
I would be immensely grateful if someone could suggest how I might be able to sort by the the first_name of the Person associated with the Quote. I suspect my syntax is wrong, but I have not been able to find the answer. Is it not possible to sort by a second level association in this way?
I am pretty much brand new with cakephp so please be gentle.
Thanks very much in advance.
I've had the similar problem awhile back. Not with sort though. Try putting the associated table in another array.
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
change to:
echo $this->Paginator->sort('Name', array('Attendance' => 'Person.first_name'));
Hope this helps
i'm also looking for help with this.
so far i've found that you can sort multi level associations in controller's pagination options after using the linkable plugin https://github.com/Terr/linkable.
but it breaks down when you try to sort form the paginator in the view. i'm using a controller for magazine clippings. each clipping belongs to an issue and each issue belongs to a publication.
$this->paginate = array(
"recursive"=>0,
"link"=>array("Issue"=>array("Publication")),
"order"=>array("Publication.name"=>"ASC",
"limit"=>10);
after debugging $this->Paginator->params->paging->Clipping in the view, you can see that the sort is described in two separate places, "defaults" and "options". the sort info needs to be present in both for it to work in the view.
here is after setting order in controller:
[Clipping] => Array
(
[page] => 1
[current] => 10
[count] => 6685
[prevPage] =>
[nextPage] => 1
[pageCount] => 669
[defaults] => Array
(
[limit] => 10
[step] => 1
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => ASC
)
[conditions] => Array
(
)
)
[options] => Array
(
[page] => 1
[limit] => 10
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => ASC
)
[conditions] => Array
(
)
)
)
and here is after using $this->Paginator->sort("Publication","Publication.name");.
notice the options array is empty.
[Clipping] => Array
(
[page] => 1
[current] => 10
[count] => 6685
[prevPage] =>
[nextPage] => 1
[pageCount] => 669
[defaults] => Array
(
[limit] => 10
[step] => 1
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => DESC
)
[conditions] => Array
(
)
)
[options] => Array
(
[page] => 1
[limit] => 10
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
)
[conditions] => Array
(
)
)
does one really need to modify the paginator class to make this work?
UPDATE:
i found out the problem:
in the core cake controller paginator merges default and options to create the find query.
but the options array is empty when using linkable to sort. because options is listed after default it overrides default and the empty array replaces the default array of options.
solution to this is extending the paginate function inside of app_controller.php and unsetting the options array order value if it is empty:
(line 1172 in cake/libs/controller/controller.php)
if(empty($options["order"])){
unset($options["order"]);
}
then the options will not be overwritten by thte blank array.
of course this should not be changed inside of controller.php, but put it in app_controller.php and move it to your app folder.
On CakePHP 3 this problem can be solved by adding 'sortWhitelist' params to $this->paginate on your controller.
$this->paginate = [
// ...
'sortWhitelist' => ['id', 'status', 'Attendance.Person.first_name']
];
And then in your view:
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
This is noted in the docs:
This option is required when you want to sort on any associated data, or computed fields that may be part of your pagination query:
However that could be easily missed by tired eyes, so hope this helps someone out there!

Categories