In CakePHP, is there a better way to select the users name? - cakephp

I currently have a users table and a posts table. My posts table has a field for user_id, however, I am not sure how I would grab the users name field which is in the users table. I was thinking of using the models afterFind() method and then using SQL to select the data, but there has to be a better way than this. Also, on my view action, I am using the read() function to grab a single post. Would the models afterFind() kick in after it runs read()? If not, is there an equivalent such as afterRead()?

Just make an association of Post belongsTo User, and every regular find/read operation that has a sufficiently high recursive value will automatically fetch the user with each post.
$post = $this->Post->find(...);
echo $post['User']['name'];

you have to go like below :
$this->Cake->findById(7); Cake.id = 7
here , you can you use your user_id instead of 7 like..
Find BY CAKE PHP

$this->Post->bindModel(array('belongsTo'=>'User'));
$post = $this->Post->findById($post_id);
$userName = $post['User']['name'];
Here are errors, I've typed it in eclipse (:

Related

Laravel get value of column from relation through pivot on load() after all()

I have a problem retrieving values of a column from relations in Laravel.
I have a User - Model. This model has relation to a table btw. a model named Userhobbies.
For now we have:
User ::: hasMany >>> Userhobbies
Now with User::all()->load('hobbies') I'm getting right results like
{"id":"1","username":"jdoe","first_name":"Joe","last_name":"Doe","birth":"
1992-04-11","picture_id":"f3dca65323e876026b409b9ba3d49c56","hobbies":
[{"hobby_id":"1","user_id":"1"},{"hobby_id":"2","user_id":"1"},
{"hobby_id":"3","user_id":"1"},{"hobby_id":"4","user_id":"1"}]}
As you can see Userhobbies contains only primary-key relations between hobby - table (Hobby Model) and user - table (User Model).
(Hobby model also has hasMany relation to Userhobbies)
My question now is - how to retrieve all hobby-names (from hobby - table) in my call over (after load('hobbies') ) and is it possible without writting a lot of code?
For better understanding of my idea the result which I want to retrieve:
{"id":"1","username":"jdoe","first_name":"Joe","last_name":"Doe","birth":"
1992-04-11","picture_id":"f3dca65323e876026b409b9ba3d49c56","hobbies":
["golf", "cards", "games", "football"]}
EDIT:
If I try following (I tried with belongsToMany in User and Hobby):
User::with('hobbies')->get()->first()
And I'm getting the whole values from the hobbies - table:
{user-specific data ...
hobbies:[{"id":"1","name":"golf","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"1"}},
{"id":"2","name":"cards","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"2"}},
{"id":"3","name":"games","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"3"}},
{"id":"4","name":"football","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"4"}}]}
Same try with ->load('hobbies'). I really don't know how to go on.
To explain it a bit more what I need one could imagine such query as follows:
User::all(['id', 'name'])->load(array('hobbies.id','hobbies.name'))->get();
From my knowledge, I know that it's possible to use a closure to set constraints on the query that performs the load, like so:
User::all()->load(['hobbies' => function($query)
{
$query->select('id', 'name');
}]);
By doing it, when you cast it to array, it will produce a result near to what you want. You can even add 'pivot' to your $hidden property on your Hobby model to hide this information.

Wordpress get current site's db tables

I'm using multisite function in my wordpress and my database is kinda messed up (3 sites):
wp_posts
wp_2_posts
wp_3_posts
wp_comments
wp_2_comments
...
I am creating plugin which plays with database. And I need it to know which table it should take: for example, first site has to play with wp_posts, second site - with wp_2_posts and so on. Is there any variables or functions to make it happen?
If I write in query, for example select * from wp_posts this plugin will take wp_posts table in every site.
You need to use BLOG_ID_CURRENT_SITE constant, which retrieve current blog id. And to get the table prefix of current blog e.g: wp_BLOGID_ you can use $wpdb method get_blog_prefix().
$blog_prefix = $wpdb->get_blog_prefix(BLOG_ID_CURRENT_SITE); // wp_posts or wp_2_posts so on..
Then you can use your query like this:
"SELECT * FROM " . $blog_prefix . "posts"
You have to make use of the wpdb class (check the link) there you'll find a lot of info about manipulating the database.
The class gets automatically the current site database.
To get data from the database without have to hardcode the table names, you have to:
<?php
global $wpdb;
//This is the name of the post table
echo $wpdb->posts
$wpdb->query("SELECT * FROM $wpdb->posts WHERE post_status = 'publish'");
?>
Sorry for bad english.

pull Drupal field values with db_query() or db_select()

I've created a content type in Drupal 7 with 5 or 6 fields. Now I want to use a function to query them in a hook_view call back. I thought I would query the node table but all I get back are the nid and title. How do I get back the values for my created fields using the database abstraction API?
Drupal stores the fields in other tables and can automatically join them in. The storage varies depending on how the field is configured so the easiest way to access them is by using an EntityFieldQuery. It'll handle the complexity of joining all your fields in. There's some good examples of how to use it here: http://drupal.org/node/1343708
But if you're working in hook_view, you should already be able access the values, they're loaded into the $node object that's passed in as a parameter. Try running:
debug($node);
In your hook and you should see all the properties.
If you already known the ID of the nodes (nid) you want to load, you should use the node_load_multiple() to load them. This will load the complete need with all fields value. To search the node id, EntityFieldQuery is the recommended way but it has some limitations. You can also use the database API to query the node table for the nid (and revision ID, vid) of your nodes, then load them using node_load_multiple().
Loading a complete load can have performance impacts since it will load way more data than what you need. If this prove to be an issue, you can either try do directly access to field storage tables (if your fields values are stored in your SQL database). The schema of these tables is buld dynamicaly depedning on the fields types, cardinality and other settings. You will have to dig into your database schema to figure it out. And it will probably change as soon as you change something on your fields.
Another solution, is to build stub node entities and to use field_attach_load() with a $options['field_id'] value to only load the value of a specific field. But this require a good knowledge and understanding of the Field API.
See How to use EntityFieldQuery article in Drupal Community Documentation.
Creating A Query
Here is a basic query looking for all articles with a photo that are
tagged as a particular faculty member and published this year. In the
last 5 lines of the code below, the $result variable is populated with
an associative array with the first key being the entity type and the
second key being the entity id (e.g., $result['node'][12322] = partial
node data). Note the $result won't have the 'node' key when it's
empty, thus the check using isset, this is explained here.
Example:
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', 1)
->fieldCondition('field_news_types', 'value', 'spotlight', '=')
->fieldCondition('field_photo', 'fid', 'NULL', '!=')
->fieldCondition('field_faculty_tag', 'tid', $value)
->fieldCondition('field_news_publishdate', 'value', $year. '%', 'like')
->fieldOrderBy('field_photo', 'fid', 'DESC')
->range(0, 10)
->addMetaData('account', user_load(1)); // Run the query as user 1.
$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids);
}
?>
Other resources
EntityFieldQuery on api.drupal.org
Building Energy.gov without Views

CakePHP - Post type without dB table

What's the best way of doing this in cakephp:
I have a Posts model+view+controller with a "Post type" field in my database - linking to my post type id.
The post type ids are:
- Preview
- Review
- News
What I'm asking is: What's the best way (natively) of retrieving the post type name, without creating a table Post_types and linking it with a post_id.
I tried creating an array in the config lists, it worked but I think it can be better then this.
You could use the afterFind method of your Post model and add there a post_type field to your results. See also the cookbook.
From what I understand your post_type is a enum field with values preview, review, news or a varchar in which you know only add these 3 types, right?
You could try the following query
SELECT DISTINCT(post_type) FROM posts;
This will return all post_types that are being used in your posts table.
In Cake you could do this either with the find or query method.
# Using find
$this->Post->find('all', array(
'fields' => array('DISTINCT(post_type)')
);
# Or using the query directly (maybe easier in this case)
$this->Post->query("SELECT DISTINCT(post_type) FROM posts;");
associate your table posts with the table post_types with $hasOne.
With a e.g.
$this->Post->find('all');
you would get the post and the post_type in one array.

Find list in cakephp

Would recursive=-1 help in case of find("list") in cakephp. I mean any performance benefit
With the default
$this->Post->find('list');
CakePHP make this query:
SELECT `Post`.`id`, `Post`.`name` FROM `posts` AS `Post` WHERE 1 = 1
No recursive query, so changing that command will not improve the query
No, recursive=-1 will not help full in case of $this->Model->find('list').
If you want to find('all') or find('first') , then it will be more use full.
eg. User , VatInfo , VatInfoLog are three models then
1) recursive=-1
$this->VatInfo->find('all')
Will return only VatInfo table data.
2) recursive=0
$this->VatInfo->find('all')
Will return $belongsTo User And VatInfo 2 tables data.
3) recursive=1
$this->VatInfo->find('all')
Will return $belongsTo User ,$hasMany VatInfoLog And VatInfo 3 tables data.
Try it!
In debug mode Cake shows you the running time of each query. Try both ways and see if anything changes. My guess is no, since it's only taking data from one table anyway for list queries.

Resources