Laravel eloquent return both where conditions - php

Hello I have a table ideas and I want to return the rows where the user_id = with the authenticated user id plus the rows where category_id = lets suppose is array [1, 2, 3].
Disclaimer: i want both of the conditions to be returned!

Seems like that:
i think that your table ideas and model Idea associated with this have the next structure:
id, user_id, category_id and some other fields...
To get Authenticated user you can do Auth::user();
So, you can do something like this:
$categoryIds = [1, 2, 3];
$authUserId = Auth::user()->id;
$ideas = Idea::where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();
If you need relations to be extracted with the query you can add with statement:
$ideas = Idea::with('categories')->where('user_id', $authUserId)->whereIn('category_id', $categoryIds)->get();
ofc, you need to set realtions in your models
Also you can set relation in user model and get records associated with the user:
User.php
public function ideas() {
return $this->hasMany('App\Idea');
}
somewhere in code:
$categoryIds = [1, 2, 3];
Auth()->user()->ideas()->whereIn('category_id', $categoryIds)->get();
UPDATE:
To do some form of join you can use this:
$userIdeas = Idea::where('user_id', Auth::user()->id)->get();
$categoryIds = [1, 2, 3];
$categoryIdeas = Idea::where('user_id', '<>', Auth::user()->id)->whereId('category_id', $categoryIds)->get();
$mergedIdeas = $userIdeas->merge($categoryIdeas);
AND AT LAST. To do it in one query:
$userId = Auth::user()->id;
$categoryIds = [1, 2, 3];
$ideas = Idea::where('user_id', $userId)->orWhere(function($query) use ($categoryIds) {
$query->where('user_id', '<>', $userId)->whereIn('category_id', $categoryIds);
})->get();

Im having a bit of a problem knowing what you want but
If you want the results for authenticated users id and category ids you could
$category_ids = [1, 2, 3];
$model->where('category_id', auth()->user->id)->whereIn('user_id', $ids)->get();
If you want the results for either the authenticated user or where the category_ids is in the array you could
$category_ids = [1,2,3];
$model->orWhere(function($q) use($category_ids) {
$q->where('category_id', auth()->user->id);
$q->whereIn('user_id', $category_ids);
})->get();
Note that this will break if the user is not authed, but I leave that to you to do.

Related

How to make a DB call with an array of ids and get the first row of every of those ids? [duplicate]

I want to make query in Laravel Eloquent like here its raw MySQL query
SELECT * from exampleTbl where id in(1,2,3,4)
I have tried this in Laravel Eloquent but it's not working
DB::where("id IN(23,25)")->get()
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
Syntax:
$data = Model::whereIn('field_name', [1, 2, 3])->get();
Use for Users Model
$usersList = Users::whereIn('id', [1, 2, 3])->get();
As #Raheel Answered it will be fine but if you are working with Laravel 6/7
Then use Eloquent whereIn Query.
Example1:
$users = User::wherein('id',[1,2,3])->get();
Example2:
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();
Example3:
$ids = [1,2,3];
$users = User::wherein('id',$ids)->get();
Since Laravel 5.7, there is a method whereIntegerInRaw. The execution time is faster than whereIn.
User::whereIn('id', [1, 2, 3])->get();
User::whereIntegerInRaw('id', [1, 2, 3])->get();
You can see the PR.
Maybe you wanna use whereRaw($query)
Your Code :
DB::where("id IN(23,25)")->get()
Into :
DB::whereRaw("id IN(23,25)")->get()

find reviews has more than one tag. in many to many polymorphic laravel relation

hi I'm trying to use many to many polymorphic but somehow it doesnt work
I couldn't get related reviews in many-to-many polymorphic relation
I want get a review by tags, selected by customer
Table Structure:
review
> id - integer
> name - string
tags
> id - integer
> name - string
taggables
> tag_id - integer
> taggable_id - integer
> taggable_type - string
Models:
class Tag extends Eloquent
{
public function reviews()
{
return $this->morphedByMany(Review::class, 'taggable');
}
}
class Review extends Eloquent
{
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
the request from customer [tag_id_1,tag_id_2,tag_id_3,tag_id_4]
the request like [1, 2, 3, 4, 5]
array of tags-key
if a review related to this tags find and get the review, i tried something like that
Code for return related reviews:
return Review::join('taggables', 'taggables.taggable_id', '=', 'reviews.id')
->where('taggables.taggable_type', '=', Review::class)
->whereIn('taggables.tag_id', [1, 2, 3, 4, 5])
->groupBy('reviews.id')
->orderBy('name', 'asc')
->get();
OR:
Review::WhereHas('tags', function ($query) {
$query->whereIn('tags_id', [1, 2, 3, 4, 5]);
})->get();
the result i need:
The only reviews that should have these tags
review:{
name: "Review",
tags :[1, 2, 3, 4, 5]
}
laravel eloquent relationships many-to-many-polymorphic
If you want the review that has all tags, this is one way to do it:
$tagIds = [1,2,3,4,5];
$reviews = Review::query();
foreach($tagIds as $id){
$reviews->whereHas('tags', function($query) use ($id) {
return $query->where('id', $id);
});
}
$reviewsWithAllThoseIds = $reviews->get();
//if you don't want to use foreach.
collect($tagIds)->each(function($id) use ($reviews){
$reviews->whereHas('tags', function($q) use ($id) {
return $q->where('id', $id);
});
});
This should give you the reviews that has all tags that has the ids in the array.
you have a typo in your query.correct form of taggables.tagable_id should be taggables.taggable_id. I don't know this is the problem or not but suggest to write your code like below.
in the review model define relations like this:
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable','taggables','taggable_id','tag_id');
}
and in Tag model define relation like :
public function reviews()
{
return $this->morphedByMany(Review::class, 'taggable','taggables','tag_id','taggable_id');
}
and when you want return reviews of a specific tag do it like:
$tag=Tag::find(1);
$tagReviews=$tag->reviews;

Laravel whereIn issue

Good day,
I wanted to do something like this:
$ids = [1, 2, 3];
$posts = $user->posts()->whereIn('id', $ids)->get();
but I get an Internal Server Error. Is there a different way to do this?
For the sake of this example, assume ID is not the primary key and that multiple posts can have the same ID. So this:
$ids = [1, 2, 3];
$posts = Post::whereIn('id', $ids)->get();
wouldn't return the desired results.
The reason you are having the error is mysql is unable to what table you are referring with id column. Use tableName in whereIn() clouse
$posts = $user->posts()->whereIn('posts.id', $ids)->get();
N.B: I assume your Post table name is posts
please use like
$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
link : Laravel ->where('id', ARRAY). multiple where conditions laravel 4
And
User::select('id','name','email','phone','created_at')->whereIN('id',[1,2,3,4,5,6,7,8,9,9,10,11])->where('is_guest',NULL)->where('user_type','1')->orderBy('id','desc')->take(20)->get();
also work with laravel 5.4

Preserve the initial order of array in Symfony2 Doctrine findBy()

I have an array ($newsList) of IDs with the following values: 4,2,1,3.
I'm trying to get some data from the database from entity:
$news=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $newsList));
$newsList array represents real IDs from the News entity.
But when I do:
foreach($news as $n){
$n->getId();
}
IDs are in order: 1,2,3,4.
How can I preserve the order from beginning in foreach?
You can't.
It's how it's returned from DB. If you won't specify ORDER BY clause in query, database will return rows as they are in storage, and this is usually the same as id ASC.
You should sort them on your own in PHP.
You can use usort and the spaceship operator:
$newsList = [4, 2, 1, 3];
$news = $this->getDoctrine()->getRepository(News::class)->findBy(['id' => $newsList]);
$order = array_flip($newsList);
usort($news, function($a, $b) use ($order) {
return $order[$a->getId()] <=> $order[$b->getId()];
});
// $news is now ordered by id 4,2,1,3
As you are doing a global query, you can just order your results by a given property, and a given sort order, so as pointed by the previous answer, you can't.
To have your results ordered exactly as the array you given, you can do this:
$newsList = [3, 1, 4, 2];
$newsRepo = $this->getDoctrine()->getRepository('Bundle:News');
foreach ($newsList as $id) {
$new = $newsRepo->findOneBy['id' => $id];
if ($new !== null) {
$news[] = $new;
}
}
Like this, your results are ordered exactly like $newsList, e.g:
foreach ($news as $n) {
print $n->getId();
}
// Output: 3 1 4 2
IMO the best solution is to use field function to get proper news order:
$ids = [4, 1, 2, 3];
$news = $this->getDoctrine()->getRepository('Bundle:News')->createQueryBuilder('n')
->select('n, field(n.id, :ids) as HIDDEN field')
->where("n.id IN (:ids)")
->setParameter('ids', $ids )
->orderBy(field)
->getQuery()
->getResult();
Note: this solution require custom field function that can be found here.
Try this:
$news = $this->getDoctrine()->getRepository('Bundle:News')->createQueryBuilder('n')
->where("n.id IN(:Ids)")
->setParameter('Ids', $newsList ) // $newsList = array(1,2,3,4,...)
->getQuery()
->getResult();
I don't know if you can actually get them sorted from the returning query results, but you can do either of these options:
Do a foreach loop and execute 'findByOne' for each result:
foreach($newsList as $id) {
$news[]=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $id));
}
Order the results of the query afterwards:
$news=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $newsList));
foreach($newsList as $id) {
$sorted_news[] = $news[$id];
}

Method to get all items with `where` and pivot table[Laravel 5]

I need to get all items where project_group.admin_id' equal to current user id.
This find method will return just one item:
$projects = Group::find(1) -> projects()->where('project_group.admin_id', '=',Auth::user()->id)->get();
Is there any why to solve this?
Correct answer:
public function userProjects(){
$adminIdCondition = function($q){
$q->where('admin_id', Auth::user()->admin_id);
};
$projects = Project::with(['groups' => $adminIdCondition])
->whereHas('groups', $adminIdCondition)
->get();
return $projects;
}

Categories