php - 用于查找多级数组的 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”里面获取相关问题怎么办?
解决方案
据我所知,您可以使用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');
推荐阅读
- php - 在静态函数中获取静态类的属性?
- vba - 如何对用户表单填充的数据进行顺序编号
- java - DateTime addmonths 方法是增加 1 天
- python - AttributeError:模块 'serial' 没有属性 'reset_input_buffer'
- python - Python 脚本的意外输出
- python - 如何根据python中的一天中的时间每分钟从最大值和最小值计算曝光时间
- c++ - 将 R 值临时对象推回向量是如何工作的?
- macos - SwiftUI 2.0 在 macOS 上禁用窗口的缩放按钮
- r - 在不切断图形或丢失数据的情况下更改 ggplot 中的 y 轴限制
- flutter - 如何遍历 Flutter dart 中的类列表并在每个类上调用一个静态方法?