首页 > 解决方案 > 用于查找多级数组的 Laravel 雄辩关系

问题描述

我是 laravel 的初学者,我想创建一个嵌套 api,其中一个模型使用 hasmany 关系与另一个模型连接:模型 1:

    class Project extends Model
{
    use HasFactory;

    protected $table = 'projects';
    public $timestamps = true;

    protected $fillable = [
        'title','description'
         ];

         function categorywithqestions()
         {
            return $this->hasMany('App\Models\questionmd','cat','id');


            
         }
}

型号 2:

class questionmd extends Model
{
    use HasFactory;

    protected $table = 'questions';
    public $timestamps = true;

protected $fillable = [
        'title',
        'description',
        'cat',
        'q_type',
        
        ];


    function relatedquestions()
         {
            return $this->hasMany('App\Models\relatedquestion','question_id','id');
         }



}

模型 3:

class relatedquestion extends Model
{
    use HasFactory;

    protected $table = 'related_questions';
    public $timestamps = true;

protected $fillable = [
        'question_id',
        'title',
        'description',
        
        ];

      
}

这是控制器:

$callback = function($query) {
    $query->where('q_type', '=', 'direct_ask');
};
$questionmd = Project::whereHas('categorywithqestions', $callback)
->with(['categorywithqestions' => $callback])->get();



  
    return response()->json(['message' => 'Success', 'status' => 200,'data'=>$questionmd]);

我也想在“categorywithqestions”里面获取相关问题怎么办?

标签: phplaravelpopulateeloquent-relationship

解决方案


据我所知,您可以使用hasManyThrough助手。

数据库结构应该是这样的。

1 项目有很多类别 1 类别有很多问题

projects
    id - integer
    name - string

categories
    id - integer
    project_id - integer
    name - string

questions
    id - integer
    category_id- integer
    commit_hash - string

在项目模型上你可以这样做

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    /**
     * Get all of the deployments for the project.
     */
    public function deployments()
    {
        return $this->hasManyThrough(Deployment::class, Environment::class);
    }
}

稍后在您的查询中,您可以进行

$questions = Project::all()->load('questions');

推荐阅读