【问题标题】:Laravel Sql query groupBy and OrderLaravel Sql 查询组按顺序
【发布时间】:2021-11-24 09:03:12
【问题描述】:

我需要一些帮助来进行查询。

Database tabless

例子: 用户插入了一个演员姓名(姓名和姓氏),我需要遍历所有电影然后检索哪个类别出现次数更多。

我需要一些帮助来进行查询(这只是一个草图):

$src=array("Leonardo","DiCaprio");
     $film2=film::with('category')->with('actor')->wherehas('actor', function($q) use($src){
                                  $q->where('first_name', $src[0])->where('last_name', $src[1]);
                                })->wherehas('category', function($qr){
                                  $qr->groupBy('name')->orderBy('name', 'DESC');
                                })->FIRST();

模型电影:

class film extends Model{
    protected $table = "film";  
    protected $primaryKey = 'film_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['film_id', 'title', 'length'];

    public function category(){
         return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
    }
    public function actor(){
          return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
    }
}

模特演员:

class actor extends Model{
    protected $primaryKey = 'actor_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['actor_id', 'first_name', 'last_name']; 
}

型号分类:

class category extends Model{
    protected $table = "category";
    protected $primaryKey = 'category_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['category_id','name'];


    public function film(){
        return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
    }
}

【问题讨论】:

    标签: mysql sql laravel


    【解决方案1】:

    这里是解决方案:

    在 Actor.php 中添加 Join

     public function filmActor(){
         return $this->hasMany(FilmActor::class, 'actor_id','actor_id');
     }
    

    使用 filmActor 连接表查找演员

     $src=array("Leonardo","DiCaprio");
     $actor=Actor::whereHas('filmActor')->where(['first_name' => $src[0],'last_name'=> $src[1]])->first();
    

    将film_id放入数组

     foreach($actor->filmActor as $film){
          $filmIds[]=$film->film_id;
     }
    

    获取具有 filmIds 的 FilmCategory

    $filmCategory=FilmCategory::whereIn('film_id',$filmIds)->get();
    

    将 category_id 放入数组中

     foreach($filmCategory as $category){
          $categoryIds[]=$category->category_id;
     }
    

    计算重复的 category_id 有多少

     $count =array_count_values($categoryIds);
    

    获取更高的计数 $max = max($count); 获取max的key是category_id $key = array_search($max, $count);

    这是出现次数较多的类别。

     $category=Category::where('category_id',$key)->first();
    

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多