I'm trying to load last 5 comments with related posts selecting only id and title from post.
In first case I decided get all columns from posts:
Comment::with(['post'])->take(5)->orderBy('id', 'desc')->get();
And it's working fine.
But when I try get only two columns ("id, title") then nothing from posts is loaded.
Comment::with(['post:id,title'])->take($number)->orderBy('id', 'desc')->get();
I did a test and when I removed "orderBy('id', 'desc')" then was fine again.
Comment::with(['post:id,title'])->take($number)->get();
So must be some problem with "orderBy" option.
Is it any way to fix it? It's mean get only selected columns from "posts" table and order results from the last one?
Thank you.
As both your Comment and Post models contain id, Laravel doesn't know by which one do you want to sort. So, add a table name to your orderBy:
Comment::with(['post:id,title'])->take($number)->orderBy('comments.id', 'desc')->get();
Here comments is name of your table/entity, maybe it is comment.
Related
I am building a comment, with replies system using CakePHP and Backbone. But I am having some issues with my CakePHP query, that does not order in the way it needs to be.
So this is database system I have right now,
Posts
ID (Auto, PK)
MainPost (Long Text)
Timestamp
User_id
Comments
ID (Auto, PK)
SubComment (Long Text)
Timestamp
User_id
Post_id (FK, linking to the Posts table)
Now I think my model is ok (if needed I can post that code). I can save and update the posts and comments. But what I need to when a new comment is added to the system. That whole post is moved to the top.
This is the query I have done on my Posts Table,
$Table->find('all')
->contain(['Comments',
'Comments.Users',
])
// ->order(['Posts.Comments.timestamp' => 'DESC'])
// ->matching('Comments', function ($q) {
// return $q->where(['Comments.timestamp' => 'DESC']);
// })
->toArray();
So I want to do a sort, like my order looks above, I basically want to order my Posts Table based on the timestamp of my Comments Table.
When I run this query, with order enabled, it just says that "Unknown column" but I don't know why? I have a LeftJoin in my model linking the Comments to my Posts table.
I have tried doing sorts and orders within the contain call of the query, however these just sort/order the comments and not the posts!
So what am I doing wrong?
I have a database schema that goes like this:
Section
id
name
Subsection
id
name
section_id
Category
id
name
subsection_id
SubCategory
id
name
category_id
Product
id
name
subcategory_id
As you can see, each table has a foreign key that references the previous table. The problem comes when I try to get, for example, the Section from the current product or get all products from one section. So far I have tried this:
Section::with('product')->find(1)->product;
But I get this:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'product.section_id' in 'where clause' (SQL: select *
from products where products.section_id in
(1))
1 - This makes me think I need to set up a section_id in the products table to make this work. Is this correct?
2 - Shouldn't the Laravel ORM automatically go up the table hierarchy from Product to Section and get the results?
3 - Is there a way to do this maintaining my current table structure, I mean, without adding extra fields in the tables for the foreign keys?
Thanks.
No that is one way to do it but it isn't the only way.
No, how would it know that automatically?
I believe so and you can always create a specific query when laravel relationships don't work for you.
Okay first this assumes you have relationships setup on all the models to access the one below it. If that isn't the case you will need to setup the relationships.
Section::with('subsection.category.subcategory.product')->get();
I've never tried such extreme nesting but I believe this will work. The Laravel Docs talk about eager loading and scroll to see the nested example.
Another item that comes to mind is the hasManyThrough relationship. You couldn't do it for this number deep but it may be something you want to look into.
A brief summary from the docs is taking the first three from your example, Section, Subsection, and Category and then in the section class you would have this relationship.
public function category()
{
return $this->hasManyThrough('Category', 'SubSection');
}
The laravel docs with more information.
i have problem with multi category for page in php and mysql,
i have "Business" , "Category" and "Business_con_Category" tables in mysql.
the Business_con_Category table is connect between Business to Category,
so i think doing select multiple, and implode for add to table.
but my problem is editing how i can know if remove category and delete from table ?
i treid in to array old category and new category and compare, but is not work good..
do you have an idea
thanks!
An easy solution is to not try to remove only some rows from business_con_category. Instead, remove all rows for the given business, and then add the rows with the categories that still should be present.
Some difficulties with "condition"
I have a table Tags with fields : id, name, count
I have table PagesTags with fields : id, page_id and tag_id
I have table Pages with several fields : id, name, shownmenu, onilne.
In my TagsController, I have a simple code to extract and display the Tags
function tagsList(){
//$this->loadModel('PageTag');
return $this->Tag->find('all',
array('order'=>'name ASC','conditions'=>array('Tag.count >= 0')));
}
The problem is, I do not want to display the tags associated to a page which is Offline.
Then in my aboce I should use somethink like $this->loadModel('PageTag'); to get the Id of the associated page and a second $this->loadModel('Page');
to get the page status 'online' (true/false)
Can we do it at once?
How can I do it simply?
How can I look in two table at one?
You need to use model relationships to link your models together. Read the manual about it or see my answer on this topic here:
CakePHP 1.3 - Unknown column in where clause
In your case, PagesTags hasOne Page and hasMany Tags. You will write these relationships into the model. Also you will write into Tags model that it hasOne PagesTags, which will in turn retrieve the associated Page.
After you have done all of that, you don't need to call loadModel, you just query Tag and it will implicitly join the associated PagesTags and Page records, so you can just put this into your conditions:
'Page.status !=' => 'Offline'
I think the relation of the table is HABTM so you have to look this component for searching http://bakery.cakephp.org/articles/Kumazatheef/2008/10/22/habtm-searching
I'm stuck in a problem and I can't find a solution to this, it's annoying me.
I've two tables, one called contacts and the other one called phonebooks and they are linked with a third table called *contacts_phonebooks*, this is a many-to-many relationship summarize below:
contacts: id (pk)
phonebooks: id (pk)
contacts_phonebooks: contactid (fk), phonebooksid (fk)
Pretty simple and clear, and it works.
I'm using Laravel 4 and Eloquent ORM, everythings works fine when I've to fetch it, insert it and delete it but when I need to update a contact I fail miserably. I've a form that has a number of checkboxes that represent all the phonebooks (every checkbox has phonebook[] as name) so when you check one of those the phonebook id will be saved in the *contacts_phonebooks* with the contact id.
The problem is that this is not true! I mean when I run this code:
$contact = Contact::find($id);
$contact->contact_name = Input::get('newCName');
$contact->contact_surname = Input::get('newCSurname');
$contact->contact_email = Input::get('newCEmail');
$contact->contact_phone = Input::get('newCPhone');
$contact->contact_birth = Input::get('newCDate');
$contact->phonebooks()->sync(Input::get('phonebook'));
if($contact->save())
{
return "TEST DONE?";
}
It deletes every row in *contacts_phonebooks* associated with the contact id and save only the new one checked... This is weird I know, I try to explain it better.
I want to update Mr.x and he actually is in "Stackoverflow" phonebook, I want to add him in "Nerd" phonebook so I click on update and I selected "Nerd", the other one is already selected.
When I update him the system deletes the "Stackoverflow" link and save ONLY the "Nerd" phonebook (with the code above) this things driving me crazy because Laravel 4 Doc says that you should use the sync() method in order to update a many-to-many relationship.
I don't how how to solve it, I hope you will understand what's my problem.
Cheers.
The documentation says "The sync method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model:"
So what I think you are probably looking for is attach().
$contact->phonebooks()->attach(Input::get('phonebook'));
Then you will have to use detach() to remove him from the other.
As stated in the docs: The sync method accepts an array of IDs to place on the pivot table.
Your pivot table should be named
contact_phonebook
and it specifies that in Laravel's documentation.