gpt4 book ai didi

laravel - 用eloquent获取外键名称

转载 作者:行者123 更新时间:2023-12-04 04:54:33 25 4
gpt4 key购买 nike

这一定是非常基本的东西,但我似乎无法找到如何去做。

我在表之间有一对多的关系:单位和军队(军队包含许多单位),这些是我的模型:

class Army extends Eloquent {
protected $guarded = array();

public static $armies = array();

protected $table = 'armies';

public function units()
{
return $this->hasMany('Unit');
}

}

和:
class Unit extends Eloquent {
protected $guarded = array();

public static $units = array();

protected $table = 'units';

public function armies()
{
return $this->belongsTo('Army', 'army');
}


}

因此,在我的单位表中,我有一行名为“军队”,其中包含与该单位相关的军队的 id,我想以以下方式在我的 View 中显示一个简单的 ul 列表(我希望它显示在单位上索引 View ):
 <ul>
<li>Army 1 name
<li>Unit 1 of Army 1</li>
<li>Unit 2 of Army 1</li>
</li>
<li>Army 2 name
<li>Unit 1 of Army 2</li>
<li>Unit 2 of Army 2</li>
</li>
</ul>

为此,我的单位 Controller 如下所示:
class UnitsController extends BaseController {

protected $layout = 'master';

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$units = Unit::all();

$this->layout->content = View::make('units.index', compact('units'));


}
/*Other stuff*/
}

在我看来( View /单位内的 index.blade.php):
<ul class="units">
@foreach($units as $unit)
{{$unit->army}}
<li>
{{ HTML::link(route('units.show', ['units' => $unit->id]), $unit->name)}}
</li>
@endforeach
</ul>

但是 {{$unit->army}} 只是(当然)显示军队的 id,我想要名字,我该怎么做?

最佳答案

假设您已正确设置架构:军队 表至少有 id (自动递增)和 单位 表至少有 id (自动递增)和 Army_id (整数,无符号),然后,试试这个:

型号

class Army extends Eloquent {
public function units()
{
return $this->hasMany('Unit');
}
}


class Unit extends Eloquent {
public function armies()
{
return $this->belongsTo('Army');
}
}

在您的 Controller 中
你想让所有军队都有单位:
$armies = Army::with('units')->get();

在您的 View 中 您想遍历结果集,输出每个军队及其各自单位的名称
@foreach($armies as $army)
{{$army->name}}
<ul>
@foreach($army->units as $aunit)
<li>
{{ $aunit->name }}
</li>
@endforeach
</ul>
@endforeach

如果这不起作用,我会吃掉我的头。

关于laravel - 用eloquent获取外键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16937085/

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