【问题标题】:Laravel Eloquent - retrieving specific columns from related modelLaravel Eloquent - 从相关模型中检索特定列
【发布时间】:2014-04-11 17:31:11
【问题描述】:

我是 Laravel 的新手,仍然对 Eloquent 有所了解。我有两个具有多对多关系的模型(A,B)(两个模型中的belongsToMany),具有以下字段:

A: id, name, text, etc..

B: id, name, description, info, etc...

A_B: id, A_id, B_id

在检索“A”对象时,我只想检索其相关“B”的“id”和“名称”,而不是整个“B”对象——因为它们可能很大。是一种仅从相关模型中检索特定列的方法,还是将我的表分开以便“id”和“name”独立?

【问题讨论】:

标签: orm laravel eloquent


【解决方案1】:

我不确定从表“B”中获取所有列是否会过多影响查询速度,但您可以试试这个:

表“A_B”的模型类

class A_B extends Eloquent {

    public function a(){
        $this->hasMany('A', 'id', 'a_id');
    }

    public function b(){
        $this->hasMany('B', 'id', 'b_id');
    }

}

在表“B”的模型中

class B extends Eloquent {
    //Hide fields from displaying in your query
    protected $hidden = array('description', 'info');
}

在您的控制器中:

//Get all records with A and B
$all = A_B::with('a')->with('b')->get();

return View::make('view')->with('all', $all);

在你看来:

@if($all->count() > 0)
    @foreach($all as $record)
        {{ $record->id }}
        {{ $record->name }}
    @endforeach
@else
    There are no records to be displayed
@endif

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2016-06-23
    • 2020-11-03
    • 2017-02-04
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多