gpt4 book ai didi

php - Eloquent 具有多对多 (belongsToMany)

转载 作者:可可西里 更新时间:2023-11-01 08:39:08 26 4
gpt4 key购买 nike

我有这个给定的表结构:

enter image description here

如何使用 Eloquent 从我的“visita”类访问“curso.name”?我分配了多对多关系,但只能访问“turma.curso_id”,但我想得到类似 $visita->curso['nome'] 的内容。

我想知道如何避免需要 Curso::all()

在下面添加了一些片段:

// Class VISITA    
class Visita extends Model
{

protected $fillable = [
'id',
'nome',
];

public function turmas()
{
return $this->belongsToMany('App\Models\Turma', 'turma_disciplina_visita')->withPivot('disciplina_id');
}

}

// Class TURMA
class Turma extends Model
{

protected $fillable = [
'id',
'nome',
'curso_id',
];

public function curso()
{
return $this->belongsTo('App\Models\Curso');
}

}

// Class CURSO
class Curso extends Model
{

protected $fillable = [
'id',
'nome',
];

public function turmas()
{
return $this->hasMany('App\Models\Turma');
}

}

// Class VISITACONTROLLER
class VisitaController extends BaseController
{

public function list($request, $response)
{
$visitas = Visita::all(); // brings me the visita and the turma with its attributes
$cursos = Curso::all(); // wanted to get cursos without needing this extra query which brings me all the cursos..

return $this->view->render($response, 'Visitas/list.php', [
'visitas' => $visitas,
'cursos' => $cursos,
]);

}
}

// View LIST.PHP

// This way I get the turma.nome
foreach ($visita->turmas as $turma){
echo $turma['nome'] . '<br>';

// This way I get the curso.nome
foreach ($visita->turmas as $turma){
echo $cursos[$turma['curso_id']] . '<br>';

最佳答案

你试过像这样加载你的收藏吗:

Visita::with('turmas.curso')->all();

并且在您的前端,您应该能够像这样加载您的数据:

foreach (($visita->turmas as $turma){
$turma->curso->nome;
}

希望对你有帮助

关于php - Eloquent 具有多对多 (belongsToMany),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com