Laravel Eloquent Filter By Column of Relationship - orm

Using the Eloquent ORM I have my models set up like so: Post belongsToMany Category
Post.php
public function categories()
{
return $this->belongsToMany('Category', 'posts_categories');
}
I want to filter posts by a column of the categories relationship.
So I want to do something like:
$posts->where('categories.slug', '=', Input::get('category_slug'));
This doesn't work though.
I also tried:
$with['categories'] = function($query){
$query->where('slug', '=', Input::get('category_slug'));
};
$posts::with($with)->get();
But I thnk that's for filtering the categories not filtering BY the category.
Can anyone show me the way?

I can't access my Vagrant box right now, but I believe this should work:
$posts = Post::whereHas('categories', function($q)
{
$q->where('slug', '=', Input::get('category_slug'));
})->get();

Here's a quick way to filter on related model column:
$allConsultants = Consultant::whereHas('user', function($query)
{
$query->where('is_approved', '=', 1);
})->get();

Related

How to make a SUM() with WHERE in HASMANY relationship on laravel? Any help is appreciated

Good evening friends, I'm having difficulty on get a SUM from a HASMANY relationship with a condition.
I was trying to do something like this:
$marketPlaces = ModelAccountMarketplace::with(['orders'])
->whereHas('orders', function ($query) use ($dates) {
$query->selectRaw('SUM(valor_frete) as somaFreteGratis')
->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
});
But when i try to get the value with: var_dump($marketPlace->somaFreteGratis);
I get a null value. I try to put the where inside the WITH() like:
$marketPlaces = ModelAccountMarketplace::with(['orders' => function ($query) {
$query->selectRaw('SUM(valor_frete) as somaFreteGratis')->where('tipo_frete', 'gratis');
}])
->whereHas('orders', function ($query) use ($dates) {
$query->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
});
But in every try i get a null value when i check with:
<?= var_dump($marketPlace->somaFreteGratis); ?>
Any help would be appreciated.
What you're trying to do can be accomplished using a withCount along with a Closure
$marketPlaces = ModelAccountMarketplace::withCount([
'orders as somaFreteGratis' => function ($query) use ($dates) {
$query->select(DB::raw('sum(valor_frete)')
->where('tipo_frete', 'gratis')
->whereBetween('datetime', [$dates['dateStart'], $dates['dateEnd']]);
}
])
->get();

How to implement "where not" in laravel eloquent query builder

What is the laravel equivalent eloquent query builder for this mysql sql snippet:
select * from `posts` left join `user_post_interactions` on `posts`.`id` = `user_post_interactions`.`post_id` where `posts`.`user_id` = 10 and not (`user_post_interactions`.`interaction_name` = 'hide' and `user_post_interactions`.`user_id` = 10)
What I am doing is:
$this->posts()->leftJoin('user_post_interactions', 'posts.id', '=', 'user_post_interactions.post_id')
->where(function($q) {
$q->where('user_post_interactions.interaction_name', '<>', 'hide')
->where('user_post_interactions.user_id', '<>', 10);
});
But this is not producing the result I expected
You can use whereHas() which will only query posts which have an interaction where the user_id does not equal 10:
$this->posts()->whereHas('interactions', function ($query) {
$query->where('user_id', '!=', 10);
})->get();
Note this will require a Interaction model with a interactions() relationship on the Post model.
If you would like to include interactions with the query, add ->with('interactions') to the query chain.
You can simply run:
$this->posts()->with(['interaction' => function($query){
return $query->where("interaction_name","!=",'hide')
->where("user_id","!=",10);
}]);
If you wants to filter having interaction
$this->posts()->whereHas('interaction', function($query){
return $query->where("interaction_name","!=",'hide')
->where("user_id","!=",10);
});
here I assume your posts table have relationship interaction

Get resultat data from an array

I'm using Laravel and I've used this query to fetch records:
<?php
foreach ($connectionUser as $value) {
if ($value->sender_profile_id == $profile_id) {
//$profileID[] = $value->receiver_profile_id;
$result[] .= $this->select('assets.id', 'assets.profile_id', 'assets.access', 'assets.name', 'assets_data.path', 'assets.processed'
->join('assets_data', 'assets.id', '=', 'assets_data.asset_id')
->where('profile_id', '=', $value->receiver_profile_id)->orderBy('assets.created_at', 'desc')
->get();
} elseif ($value->receiver_profile_id == $profile_id) {
//$profileID[] = $value->sender_profile_id;
$result[] .= $this->select('assets.id', 'assets.profile_id', 'assets.access', 'assets.name', 'assets_data.path', 'assets.processed')
->join('assets_data', 'assets.id', '=', 'assets_data.asset_id')
->where('profile_id', '=', $value->sender_profile_id)
->orderBy('assets.created_at', 'desc')
->get();
}
}
And the result look like this (print_r($result))
Array (
[0] => []
[1] => [{"id":233,"profile_id":175,"access":"PUB","name":"99","path":"Capture_233.PNG","processed":"0"}]
[2] => []
)
How can I get the result datas?
From the code you post, I guess you are trying to retrieve id, profile_id, access from assets table. For question,
any alternative way in laravel to execute above query?
It's better use to eloquent ORM instead of using raw queries. All what you have to do is define the the relationships in the model classes and use the related models as properties.
Check the Laravel Document
Getting Started with Eloquent
Eloquent Relationships
You should check the array result from the query, and check if there is a result, then you push it to $result.
To get the data after finishing that code, you can loop to the $result values (which it will be another array, if you want one result from the query you can take the first on ->first()).

Nested eager loading in where clause in Laravel

I want to know is there anyway to write query like this in Laravel using Eloquent. I mean can i do eager loading in where clause. I am stuck here from last day and i really want to do like this. So suggestions needed.
$notifications = Notification::where('user_id',Auth::user()->id)
->where('is_try', '!=', Config::get('constants.NOTIFICATION_AGAINST_JOB_TURN_DOWN'))
->where('is_try', '!=', Config::get('constants.NOTIFICATION_AGAINST_JOB_EXPIRED'))
->where(function($query) {
$query->where(function($query) {
$query->where('message', '!=', 'job_post')
->with(['suggestion' => function ($query) {
$query->with(['job' => function ($query) {
$query->with('company');
}]);
}]);
})
->orWhere(function($query){
$query->where('message','job_post')
->with(['job' => function ($query) {
$query->with('company');
}]);
});
})
->orderBy('notifications.created_at','desc')
->get();
as per my knowledge, you can load the the relationship like this $query->load('company'); instead of $query->with('company');
also you can load multiple/nested relationship like this.
Notification::with([
'rel'=>function($q){ $q->where()... //can add up where, orderby etc clauses like this},
rel.profile,
rel.profile.images,
rel.profile.images.location
])->wehre()....
also you can do this,
$course_orignal = Courses::find($course_id);
$course_orignal->load('quizzes','quizzes.questions', 'chapters','chapters.quizzes.questions','chapters.lessons','chapters.lessons.quizzes','chapters.lessons.quizzes.questions');

How can i use Yii.ActiveRecord to find unrelated records?

I have two models with relation:
class Model1 extends CActiveRecord
public function relations()
{
return array(
'relation' => array(self::HAS_MANY, 'Model2', 'id_model1'),
)
}
I want view by CListView those records from Model 1, which unrelated with Model2.
Obvious, I can use something like
$criteria->condition = 'id NOT IN (SELECT DISTINCT id_model1 FROM model2_tbl)'
and then send this $criteria to ActiveDataProvider.
But I look for something more smart, more "yii-way" for solution. Is it exist?
Relational query options 'joinType' = 'RIGHT OUTER' and 'condition'=>'left_table.join_field IS NULL' might do the trick.