codeigniter forum join problem - codeigniter

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.

Related

How Query Multiple dataset in Laravel

I am struggling to get list of places that matches current category(multiple dataset) and city:
what i did is the following,
$cat = Category::find($request->category_id)->toArray();
$cat_id = $cat['id'];
and
$places = DB::table('places')
->where('category',$cat_id)
->where('city_id', $request->city_id)
->get();
See screenshot of the dataset:
Data in the database
For your current problem, you can use the LIKE operator.
$places = DB::table('places')
->where('category','LIKE', '%"'.$cat_id.'"%')
->where('city_id', $request->city_id)
->get();
but the above code will not solve your problem permanently. It looks like you are trying to create a many to many relationship in this case the best practice to use pivot tables for this. Better if you could update the schema as an example and follow the Laravel standards to achieve this. Example:
table: category_place , having columns ["category_id", "place_id"]
in the same way, you need to update the following schema
Place Type
table: place_place_type, columns ["place_id", "place_type_id"]
Amenities
table: amenity_place, columns ["amenity_id", "place_id"]
Ref. link: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-polymorphic-relations

How do i fetch the latest comment for with that specific model, and the user for that comment?

I have a model that is "static". Its contains games with various information about them. And users can comment on games with a polymorphic relationship. The problem is that I want to fetch the 10 latest games that has been commented on, and that user for that comment. So Game doesn't have a relationship to Users.
I have manage to solve it like this:
$games = Game::join('comments', 'games.id', '=', 'comments.commentable_id')
->where('comments.commentable_type', Game::class)
->latest('comments.created_at')
->groupBy('games.id')
->take(10)
->withCount('comments')
->get()->each(function($game){
$game->comment = $game->comments()->orderBy('created_at', 'desc')->first();
$game->user = User::find($game->comment->user_id);
return $game;
});
But this creates a lot of queries, I would like to eager load, don't have that N+1 problem everyone is talking about.
I got another solution to add this function to Game
class Game extends Model {
public function latestComment() {
return $this->morphOne(Comment::class, 'commentable')->latest();
}
}
And run the query like $games = Game::withCount('comments')->with(['latestComment.user'])->take(10)->get();
But it seems as this query doesn't fetch the users. Only the first user is fetched. And also the comments_count (withCount()) only returns a value for the firsts result.
So I'm stuck!
The expected result
Load the 10 latest games with the latest comment for that game, with the totalt count of comments for that game, with the user for the latest comment - everything eager loaded to avoid the n+1 problem.
Is it possible?
ps. prepared a sqlfiddle http://www.sqlfiddle.com/#!9/c07570
Edit
It seems as the second query in this question "takes" (take(10)) takes the first 10 games in from games table, regardless if they have comments or not. If I have 15 comments for games with IDs from 20-30, the query will check IDs from 1 to 10.
If I run the second query in my question, with just the fiddle data in my comment table. Result 10 will contain game with id of 10, no user, no comments_count etc.
You can use a modified withCount() to get the latest comments.created_at:
$games = Game::withCount(['comments',
'comments as latest_comment' => function($query) {
$query->select(DB::raw('max(created_at)'));
}])
->having('comments_count', '>', 0)
->orderByDesc('latest_comment')
->with('latestComment.user')
->take(10)
->get();
I would access directly the comments table/model, query for the last 10 comments, pluck the games ids, and use them to query the games model/table with a whereIn.
Also add to the games query a selectRaw('(SELECT COUNT(*) FROM comments where ...) as commentCount')

Editing product page with dimsav/laravel-translatable

im using a package called Laravel-Translatable
but is giving me more problemns that i expect, mainly with quite simple tasks. For example i have a list of all records (products), and each of them haves 2 languages translated (en,es). But now i need to edit the product information to put in the inputs fields, and for this i wish in my edit page get all the translated details (title, description), but for some reason, is returning me only one language, it doesnt return all the translated details from a specific product:
ex: return Product::where('id', '2')->get();
Somebody uses this package?
Just read the documentation. Therein is all that you need.
Some example:
$product = Product::where('id', 2)->get();
$product->translate('de')->title = "Germany title";
$product->translateOrNew('pl')->title = "Polish title";
//Shortcut
$product->{'title:pl'} = 'lorem ipsum';
$product->save(); //It Will save all translations and main model

Not getting all the table data while executing the laravel query

Link for table
link for expected result, after group by 'receiver_user_id' and recent time
I have used the laravel query:-
$sub = BaseMessagesHistory::select('messages_history.*')->orderBy('created_at','DESC');
$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
->where('sender_user_id',$userId)
->orwhere('receiver_user_id',$userId)
->groupBy('receiver_user_id')
->havingRaw('max(created_at)')
->latest()->get();
Result:-
I am getting only "recent_time" and "receiver_user_id"
Expectation:- I need whole data from table not only "recent_time" and "receiver_user_id"
So can you please help me out
It will return you only those columns which you mentioned in the select().
In your query, you mentioned only receriver_user_id and recent_time.
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
You need to add all those columns in select() which you need.
Or try this ->select('sub.*',DB::raw('max(created_at) as recent_time'))
Hope this helps. Ask in case of doubt.

CodeIgniter Nested Query

I have a piece of code for getting conferences from database, where a specific subscriber is not subscribed.
I have two tables:
conferences - which holds all conferences
read - which holds subscriber with conferences
Here is the code, but I get MySQL 1064 error.
function getPossibleConferencesOfSubscriber($sub_id)
{
$a = "SELECT * FROM conference C where C.ISSN not in (SELECT ISSN FROM read where sub_id=$sub_id)";
$query = $this->db->query($a);
return $query->result();
}
Ok, I found the problem. I guess "read" is something like a command, so MySQL confuses the table name read and command read. I hope this helps someone, saves his 1 hour.

Resources