Post::with('comments.owner')->get();
This query will get us all the posts, its comments and comment owner .
But how can I get all the posts , its last 5 comments and authors for each comments . Can any one help please ?
Here is the schema
Posts - id - content
Comments - id - commented_id (user_id) - user_id
User - id - full_name
Thanks
Try this:
$posts = Post::with(['comments'=>function($query){
$query->orderBy('created_at','desc')->limit(5);
}])
->with('comments.author')
->get();
Related
I have something like this:
Table 1: Training Name, created_at, user_id (Plan_Treninga)
Table 2: user_id, created_at, expire_at (InvoiceUser)
I want to pull all from Table 1 where created_at is between Table 2 created_at and expire_at.
This is something what i am trying to..
$plan = Plan_Treninga::whereBetween(function($q) use ($id){
$inv = InvoiceUser::where([
["user_id",$id],
["status","paid"],
])->latest("id")->first();
})
I haven't finished it yet, but my brain stopped working so I have to ask here.
If I understand what you want clearly is. you want to query all from table 1 which created exist between table 2 created and expire_at right? if so you can use where exist query to achieve this.
// assume your table name is plan_treningas & invoice_users
Plan_Treninga::whereExists(function ($query) {
$query->select(DB::raw(1))
->from('invoice_users')
->whereRaw('plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at'); // add more query depend your logic
})->get();
for more you can take a look at docs
or if you want to use raw query
SELECT
*
FROM plan_treningas
WHERE EXISTS (
SELECT 1 FROM invoice_users WHERE plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at
)
Take a look at joins https://laravel.com/docs/7.x/queries#joins
I am not saying this is the exact solution but I have something similar that I have changed to point you in the right direction.
With joins you can do lots of things.
$results = DB::table('table1')
->join('table2', function ($join) {
$join->on('table1.user_id', '=', 'table2.user_id')
->where('table2.status', '=', 'paid')
->where('table2.created_at', '>', 'table1.created_at');
})
->get();
Also look at relationships. There is some good answers for setting up many to many relationships.
https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
Today i encountered a problem developing my app.
I restructured my database.
I have 3 tables for posts, photos, and for the tags of the posts.
I joined the two other tables(photos, tags).
I would like to query the first 3 post with only one SELECT with photos and tags, but only the first row showing up from the results.
Heres is my code:
$this->db->select('owner, title, time, LEFT(content, 75) as content, category, url, price, county');
$this->db->from(POSTS_TABLE);
$this->db->join(PHOTOS_TABLE, PHOTOS_TABLE.'.post_id = '.POSTS_TABLE.'.url');
$this->db->join(TAGS_TABLE, TAGS_TABLE.'.post_url = '.POSTS_TABLE.'.url');
$this->db->order_by('time', 'desc');
$this->db->limit(3);
$query = $this->db->get();
$posts = $query->result();
My DB structure:
posts table:
id, owner, title, content, url
tags table: id, post_id (same as the url column from the posts table), photo (the link to the photo)
tags table:
id, post_url (same as the url column from the posts table), tag.
Please help.How can i achieve that with only one SELECT and showing up the correct results ?
I cannot use the WHERE clause, since i dont know the exact post_url
Considering column name 'url' is the id of the row
Try:
// Code before
$this->db->join('PHOTOS_TABLE', 'PHOTOS_TABLE.post_id = POSTS_TABLE.url');
$this->db->join('TAGS_TABLE', 'TAGS_TABLE.post_url = POSTS_TABLE.url');
// Code After
I have an eloquent query where I am not getting the expected results and I was hoping someone could explain to me what the correct way to write the query.
I have three tables:
records (belongsToMany users)
users (belongsToMany records)
record_user (pivot)
The record_user table also has a column for role.
I attempt to get all the records where the user has the role of either singer or songwriter:
$results = User::find(Auth::user()->id)
->records()
->wherePivot('role', 'singer')
->orWherePivot('role', 'songwriter')
->get();
Below is how the SQL syntax is generated:
select `records`.*, `record_user`.`user_id` as `pivot_user_id`,
`record_user`.`record_id` as `pivot_record_id` from `records`
inner join `record_user` on `records`.`id` = `record_user`.`property_id`
where
`record_user`.`user_id` = '1' and `record_user`.`role` = 'singer' or
`record_user`.`role` = 'songwriter'
The results for singer role are what is expected: All records where the user is the singer. The problem is the results for the songwriter: I am getting ALL songwriters and the query is not constrained by the user_id. For some reason I was expecting the songwriter role to also be constrained by the user_id - what is the correct way to write this using the eloquent syntax?
Hmm..I think you need to use an advanced where clause.
$results = Auth::user()
->records()
->where(function($query) {
$query->where('record_user.role', '=', 'singer')
->orWhere('record_user.role', '=', 'songwriter');
})
->get();
It is Laravel issue. In my case I solve it like this:
$results = Auth::user()
->records()
->wherePivot('role', 'singer')
->orWherePivot('role', 'songwriter')
->where('user_id', Auth::id())
->get();
Or use advance where clause
If your trying to get records I would do something similar to this:
User::find(Auth::user()->id)
->records()
->where(function($q){
$q->where('records.role', 'singer')
->orWhere('records.role', 'songwriter');
})->get();
Some help with many to many relationships in Laravel:
Using the example for roles and users - basically:
a table for all the roles
a table for the users
and table with user_id and role_id.
I want to add to the third table, eg Year. basically the pivot table will have user_id, role_id and year_id.
I want to be able to make a query to pull for example all users assigned a specific role in a specific year. Eg All users with role_id = 2, and year_id = 1.
Any help will be appreciated
Before answering, I would like to suggest you not to put year on database like this.
All your tables should have created_at and updated_at which should be enough for that.
To filter users like you want. You could do this:
// This queries all users that were assigned to 'admin' role within 2013.
User::join('role_users', 'role_users.user_id', '=', 'users.id')
->join('roles', 'roles.id', '=', 'role_users.role_id')
->where('roles.name', '=', 'admin')
->where(DB::raw('YEAR(role_users.created_at)', '=', '2013')
->get();
This example may not be the precise query you are looking for, but should be enough for you to come up with it.
The best way to achieve a three way relation with Eloquent is to create a model for the table representing this relation. Pivot tables is meant to be used for two way relations.
You could have then a table called roles_users_year which could have data related to this 3 way relation like a timestamp or whatever...
A very late answer to a very old question, but Laravel has supported additional intermediate (pivot) table columns of at least Laravel 5.1 judging from the documentation, which hasn't changed at least through Laravel 6.x.
You can describe these extra columns when defining your many-to-many relationship:
return $this->belongsToMany(Role::class)->withPivot('column1', 'column2');
or in your case, the below would also do the job:
return $this->belongsToMany(Role::class)->withTimestamps();
which you can then access via the pivot attribute on your model:
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Note that the pivot attribute is on the distant relationship model (a single Role) and not on the relationship itself.
To get all the Roles assigned to Users in any given year, you might create a special relationship:
// User.php
public function rolesInYear($year) {
return $this->belongsToMany(Role::class)
->wherePivot('created_at', '>=', Carbon::create($year))
->wherePivot('created_at', '<', Carbon::create($year + 1));
}
Hello all i have a problem with my forum
my forum have a categori in that i show the threads thats created on that categori, and i show the user profile picture, the user name who created and the user name who last replay on the topic.
my problem is that if there is 2 comment on a topic it will show the topic 2 times in the categori like this: http://d.pr/QxAY
and my code is this:
traad = thread
kommentare = comments
$this->db->select('*,users.profile_picture as profil_billed, forum_traad.id as traad_id,
forum_kommentare.brugernavn as comment_username');
$this->db->from('forum_traad');
$this->db->join('users', 'forum_traad.brugernavn = users.username');
$this->db->join('forum_kommentare', 'forum_traad.id = forum_kommentare.fk_forum_traad', 'left');
$this->db->where('forum_traad.fk_forum_kategori', $id);
$this->db->order_by("forum_traad.id", "DESC");
I think your problem will be solved if you use MYSQL's GROUP_CONCAT function on the comments column of your result.
By doing this you will get topic only once and the multiple comments to that topic in the comma seperated format which you can seperate in your code later.
After trying this Let Me Know.