Laravel gives me a duplicate collection data - laravel

I want to sort my data by created date with this code :
$comments = Instacomment::where('postid',$query->post['id'])->orderBy('comment.created_at', 'ASC')->paginate(10);
These are the results and Laravel gives me duplicate data! I don't know what to do !

please try join table
$comments = Instacomment::join('comments', 'instacomment.id', '=', 'comments.postid')->where('postid',$query->post['id'])->orderBy('comment.created_at', 'ASC')->paginate(10);

Related

Laravel JOIN with JSON string

I have two tables in Laravel, one is the comment table, and the second is the users table. In the comment table, I have this type of data.
For this comment table, I want to match the tags column's userid in JSON, so how can we join that userid with the user's table? here is what I tried, but that is not working as expected.
$messages = TopicComment::where('user_id', $currentUserId)
->join("users", "users.id", "=", "users.id")
->(function ($query) {
$query->whereJsonContains('tags.userid', users.id);
})
->
->get()->toArray();
with this package you can create a relation via a json field
https://github.com/staudenmeir/eloquent-json-relations
First, there seem to be a number of errors in your code.
Judging from the DB schema, there is no user_id column in your comments table and so, ::where('user_id', $currentUserId) will not work.
A similar issue occurs in your join statement. You're joining on "users.id","=","users.id" which is the same column in the same table.
There's no method called in the line with function($query). Ideally, should be a where clause.
Correct usage of whereJsonContains would be:
$query->whereJsonContains('tags', ['userid' => $currentUserId]);
Rouge arrow after that line.
And so, your final result after correcting the changes should look like:
use Illuminate\Support\Facades\DB;
...
$messages = TopicComment::join('users', 'users.id', DB::Raw("CAST(comments.tags->'$.userid' AS UNSIGNED)"))
->where(function ($query) use ($currentUserId) {
$query->whereJsonContains('tags', ['userid' => $currentUserId]);
})
->get()
->toArray();
I think the only way to extract is to use json tables.
DB::select(DB::raw("
SELECT document_types.*, jst.name
FROM document_types,
JSON_TABLE(settings, '$[*]' COLUMNS (
`userid` int(11) PATH '$.userid',
`name` varchar(255) PATH '$.name'
)) jst
inner join users on jst.userid = users.id WHERE users.id = :id"
,['id' => $currentUserId]))->get()
credit: https://dba.stackexchange.com/questions/306938/extract-json-object-inside-of-an-json-array-then-search-base-on-id
Unfortunately I don't have json functions on my mysql so the code will probably fail, maybe at least it'll help get you on the right track.
You can try this way...
eg:
<?php
$comments = DB::table('topic_comments')
->join('users', 'users.id', '=', 'topic_comments.tags->userid')
->select('topic_comments.*', 'users.name')
->get();

How to use search value contain in array field using eloquent in Laravel

I'm working on laravel array serialize. Below is serialize in controller.
public function CreateSave(CreateTestTopicRequest $request){
...code..
$testtopic->class_room_id = $request->classroom;
$testtopic->roomno = serialize($request->roomno);
...code..
}
Then, roomno will be saved to database like.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
I would like to get result. For example class_room_id = 1 and roomno only contain in roomno array. I may use command to get all as below.
$testtopics = TestTopic::where('class_room_id',1)->get();
But, I do not know to get record only class_room_id = 1 and roomno contain in array. Any advice or guidance on this would be greatly appreciated, Thanks
You can use like search in json fields
TestTopic::where('class_room_id',1)->where('roomno', 'like', '%"id": 1%')->first()
When checking for an array of values the whereIn method can be used:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$testtopics = TestTopic::where('class_room_id',1)
->whereIn('roomno', unserialize($roomno))
->get();
Multiple where statements can be combined by passing an array:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$users = TestTopic::where([
['class_room_id', '=', '1'],
['roomno', '=', $roomno],
])->get();

What is the equivalent query of laravel on this?

This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here

Laravel query builder strange result with join

I have a query
$orders = DB::table('orders')->where('user_id', $user->id)->get();
And this is what I have in view:
#foreach ($orders as $order)
{{ $order->id }}
#endforeach
It prints out 1 2 3, because the table has these three IDs.
But if I try to join, I get a rather unpredicted result.
$orders = DB::table('orders')->where('user_id', $user->id)->
leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
It gives 2 1 1. Result is the same with rightJoin() and join().
I thought this command would append row from status table to every corresponding row of orders table. Join on orders.status_id = status.id.
Can I get an intended result?
I have tried ->select('orders.*') but it did not change the result.
But still, I needed to alias everything out, as suggested in the comments here. So here is my final query.
$orders = User::find($user->id)->orders()->
select('orders.id as order_id', 'status.id as status_id',
'status.label as label', 'orders.ordered_at as ordered_at')
->leftJoin('status', 'orders.status_id', '=', 'status.id')
->get();
Probably this could be done in more pretty way, but this works.
Thank you who commented the post.
UPD: Now, I have fixed relations between my models and I can do this much simpler. As described here Laravel Many-to-one relationship
$orders = Order::with('status')->where('user_id', '=', $user->id)->get();

Active records class in CodeIgniter

Basicly i have two tables photos and users. I wanna join tables and Update colums image_max and image_min. I get error unknown colum username. In which way i can join two tabels and get data from both. My sintax is:
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);
And I get error
Unknown column username in where clause
UPDATE `photos` SET `image_max` = '', `image_min` = '' WHERE `username` = 'wwww'
apparently you need a letter on the table should say "users.username", check that.
Greetings.
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('users.username',$username);
$this->db->update('photos',$data);
You don't need to use "select and from" before upload fields, just update in this way
$data = array('image_max'=> 4, 'image_min' => 1);
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);

Resources