n0tttrui's avatar

Select movies where category...

I have rather a category system:

#Movie.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
    /**
    **/

    public function categories() {
        return $this->belongsToMany(Category::class);
    }

    public function thumbnail() {
        return url();
    }

    public function comments() {
        return $this->hasMany(MovieComment::class);
    }

}

#Category.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function movies() {
        return $this->belongsToMany(Movie::class);
    }

    
}

#Controller

 public function filme($id)
    {

        $movie = Movie::with('comments', 'categories')->where('imdb_id', $id)->first();
        //dd($movie);
        return view('movie.see', compact('movie'));

    }

#I wanted to know how can I build a query in the Eloquent go get movies that have the same categories as this?

0 likes
25 replies
InaniELHoussain's avatar

@n0tttrui you mean to get the movies that has a certain categorie? why not use

$categorie = Categorie::findOrFail($id);
$movies = $categorie->movies()->get();

otherwise you can explaine it a little bit, please.

n0tttrui's avatar

But the problem is, I have more than one category for each movie and I need to pick the movies with the same categories of film in question ...

InaniELHoussain's avatar

something like that

$idCategories= Movie::find($id)->categories()->pluck('id');


$movies = Movie::whareHas('categories', function($query) use ($idCategories) {
    // I guess here it should be a loop, but you got the idea
    $query->whereIn('id', $idCategories);
} );
1 like
n0tttrui's avatar

Each film has more than one category, I want to do a search to go get movies that have the same categories as the movie referenced .... Example: Movie # 1: Category: Action, Comedy

I want the film to look have Action and Comedy categories as ...

Final result of query:

Film # 35: Category: Action, Comedy

Film # 50: Category: Action, Comedy

The same categories ...

InaniELHoussain's avatar

@n0tttrui my query UP will give you the movies that has at least one Categorie on commun ... I guess you just need to loop over the array of ID and chain the query

n0tttrui's avatar

@InaniELHoussain your code dont work.. return:

Builder {#184 ▼
  #query: Builder {#197 ▶}
  #model: Movie {#189 ▼
    #connection: null
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: []
    #original: []
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #fillable: []
    #guarded: array:1 [▼
      0 => "*"
    ]
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    +exists: false
    +wasRecentlyCreated: false
  }
  #eagerLoad: []
  #macros: []
  #onDelete: null
  #passthru: array:11 [▼
    0 => "insert"
    1 => "insertGetId"
    2 => "getBindings"
    3 => "toSql"
    4 => "exists"
    5 => "count"
    6 => "min"
    7 => "max"
    8 => "avg"
    9 => "sum"
    10 => "getConnection"
  ]
  #scopes: []
  #removedScopes: []
}
zachleigh's avatar
Level 47

Call get() on the results.

$movies = Movie::whareHas('categories', function($query) use ($idCategories) {
    $query->whereIn('id', $idCategories);
})->get();
1 like
n0tttrui's avatar

Just one finally question @zachleigh and @InaniELHoussain ,

#How can I make restriction not to get the film used as a reference? I tried:

$movies = Movie::whereHas('categories', function($query) use ($idCategories) {
            // I guess here it should be a loop, but you got the idea
            foreach($idCategories as $idCategory)
                $query->whereIn('category_id', $idCategory);
        })->where('imdb_id', '!=', $imdb_id)->get();

if i put this way, works, but i think incorrect :

$movies = Movie::whereHas('categories', function($query) use ($idCategories) {
            // I guess here it should be a loop, but you got the idea
            foreach($idCategories as $idCategory)
                $query->whereIn('category_id', $idCategory);
        })->where('imdb_id', '!=' . $imdb_id)->get();
rosehays's avatar

The aforementioned SQL query chooses the movie title, the actor's first and last names, and the part they played in the film. Actors who have starred in at least two films are the only ones that are included.

The JOIN clause uses the mov_id column to join the movie table and the movie_cast table. It then uses the act_id column from the movie_cast table to join the actor table.

The WHERE clause limits the results to only actors with at least two film credits. It retrieves all the act_ids that exist in the movie_cast table at least twice using a subquery and then only includes the results where the actor's act_id appears in the list if that actor's act_id is present... https://www.pikashowhd.com/

honista's avatar

Honista is a professionally developed application with exclusive features designed specifically for you in order to get the best possible user experience, at the same time you do not need more applications to carry out simple tasks such as viewing an account picture or downloading a video clip or image and other things which users of all social media App like: (honistamod.com) need these days.

James_alexander's avatar

You can use whereHas with get() to filter movies by categories efficiently. This method ensures you retrieve only relevant results while keeping the query optimized.

bobbyengel's avatar

This SQL snippet does a solid job pulling movie titles along with each actor’s name and the specific role they played. What really stands out is the filter that keeps only those actors who’ve appeared in two or more films — a neat way to highlight the more active performers.

The JOINs are straightforward: links movies with their cast, and connects each cast entry back to the actor table. Clean, simple, and effective. Even though there’s no URL provided, the structure is clear enough that it could easily plug into any database-backed project or reference page www.veduhd.app ...

Please or to participate in this conversation.