Laravel eloquent get data from two tables - laravel

Laravel Eloquent Query builder problem
Hello I have a problem when I am trying to get all the rows where slug = $slug.
I will explain in more details:
I have two tables, cards and card_categories.
cards has category_id.
card_categories has slug.
What I need is a query which returns all the cards which contents the slugs.
For example I made this:
$cards = Card::leftJoin('card_categories', 'cards.id', '=', 'card_categories.id')
->select('cards.*', 'card_categories.*')
->where('card_categories.slug', $slug)
->paginate(5);
But what happens is that just return 1 row per category.
I don't know what is wrong.
Many thanks.

I think I understand what you mean, from your explanation I would imagine your card model is as follows.
class Card extends Model {
protected $table = 'cards';
public function category()
{
return $this->belongsTo(Category::class)
}
}
In which case, you should just be able to do this:
$cards = Card::whereHas('category', function ($query) use ($slug) {
$query->where('slug', $slug);
})->paginate(5);
That will select all of the cards that has the category id of the given slug.

Related

Get Average from Polymorphic Relation

I am both trying to get the review counts and the average review ratings.
I have tables:
Tables:
id
.....
Chairs:
id
.....
Reviews:
id
rating
reviewable_id
reviewable_type
class Review extends Model {
public function reviewable() {
return $this->morphTo();
}
}
class Tables extends Model {
public function reviews() {
return $this->morphMany('App\Review', 'reviewable');
}
public function avg_rating() {
return $this->reviews()
->selectRaw('avg(rating) as avgRating, review_id')
->groupBy('review_id');
}
}
I've tried:
Table::with(['avg_rating'])->withCount('reviews')->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();
But get "Unknown column 'review_id' in 'field list'" or attempting it with variations of "hasmany" yielded only an empty array or an array with the reviews. Just wonder what the best way to accomplish this is or if I'd have to loop through the reviews and calculate manually or a second raw query
I have this but not sure if it is efficient or best practice within Eloquent:
$tables->each(function ($table) {
$table->review_average = DB::table('reviews')
->select(DB::raw("ROUND( avg(rating), 2) as avg"))
->where("reviewable_id", "=", $table->id)->first()->avg;
});
Apparently, I was using Lumen based on the Laravel 6 framework, so it had been throwing a "method not found" error when I tried "withAvg" before. But after searching for that method, I saw that it required a higher version of Laravel. So, updating to Laravel/Lumen 8 allowed me to use the "withAvg" function.
So now my query builder statement looks like:
Table::with(['avg_rating'])->withCount('reviews')->withAvg("reviews", "rating")->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();

Get count of votes with Eloquent in Laravel 4.2

i'm trying to get count of likes for each picture. Here is my code
$user = User::with(['pictures' => function($q){
$q->with('likes')->count();
}])
This code returns all likes as separately for each picture.
I think this count() is not working for me.
Thanks for help.
$user = User::with(['pictures' => function($q){
$q->where('likes',1)->count();
}]);
Remember to specify a relationship in User Model like so:
class Country extends \Eloquent {
public function pictures(){
return $this->hasMany('App\Models\Picture');
}
}
NB: I assumed App\Models\Picture is your pictures Model and also that 'likes' is Boolean datatype column in pictures table

How to find inverse of Eloquent query

I've got a query to find enrolled students in a particular activity. On the User model:
public function enrolledStudents($activity)
{
$students = $activity->students()
->wherePivot('user_id', $this->id)
->get();
return $students;
}
Where the Activity model's students method is this:
public function students()
{
return $this->belongsToMany('Student', 'activity_student', 'activity_id', 'student_id')
->withPivot('user_id')
->withTimestamps();
}
I want another method to find the students who aren't enrolled in this activity - how could I go about this?
I.e. $user->students()->notEnrolled($activity)
Basically, you'd have to come from the Student angle. Something like this:
$students = Student::whereDoesntHave('activities', function($q) use ($activity){
$q->where('activity_id', $activity->id);
})->get();
Note that this method is quite new, so you might need to update Laravel with composer udpate

Eloquent where condition based on a "belongs to" relationship

Let's say I have the following model:
class Movie extends Eloquent
{
public function director()
{
return $this->belongsTo('Director');
}
}
Now I'd like fetch movies using a where condition that's based on a column from the directors table.
Is there a way to achieve this? Couldn't find any documentation on conditions based on a belongs to relationship.
You may try this (Check Querying Relations on Laravel website):
$movies = Movie::whereHas('director', function($q) {
$q->where('name', 'great');
})->get();
Also if you reverse the query like:
$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();
// Access the movies collection
$movies = $directorsWithMovies->movies;
For this you need to declare a hasmany relationship in your Director model:
public function movies()
{
return $this->hasMany('Movie');
}
If you want to pass a variable into function($q) { //$variable } then
function($q) use ($variable) { //$variable }
whereBelongsTo()
For new versions of Laravel you can use whereBelongsTo().
It will look something like this:
$director = Director::find(1);
$movies = Movie::whereBelongsTo($director);
More in the docs.
is()
For one-to-one relations is() can be used.
$director = Director::find(1);
$movie = Movie::find(1);
$movie->director()->is($director);

Laravel 3 Eloquent ORM usage

I have the following code which works but doesn't seem to follow the laravel eloquent way:
Article::left_join('images', 'articles.id', '=', 'images.article_id')
->join('article_category', 'articles.id', '=', 'article_category.article_id')
->where('article_category.category_id', '=', $category_id)
->get();
I have 4 tables; articles and categories which have a many to many relationship with each other, a pivot table article_category table which holds the article id and category id and an image table which has one to one relationship with an article.
I setup my models as:
class Category extends Eloquent {
public static function get_articles($category_id) {
return static::find($category_id)->has_many_and_belongs_to('Article');
}
class Article extends Eloquent {
public function categories() {
return $this->has_many_and_belongs_to('Category');
}
public function image() {
return $this->has_one('Image');
}
However I can't seem to get all three bits of info together. I can do:
Category::get_articles($current_category)->get();
To get all articles in a given category but I can't seem to get the image for the article, there seems to be nothing I can chain onto? Unless I'm doing it incorrectly? Is there a trick I'm missing?
I even tried the stripped down version from the docs:
foreach (Article::with('image')->get() as $article) {
echo $article->image->foo;
}
However I get an error: Trying to get property of non-object, even though var_dump shows $article->image is an object! Weird.
Thanks
If you have not setup a model for the image table, do that. The ORM needs the model there so it knows what 'Image' refers to.
Can you get the category information using the ::with method or is that troublesome too?

Resources