如何在Laravel资源控制器中返回具有子模型的belongsTo模型的一个属性


How to return one property of a belongsTo model with the child model in Laravel resource controller

我使用Laravel作为SPA的REST API。我有一种家庭有多重贡献的关系。贡献表有一个指向家族id的外键引用。我可以调用hasMany/belongsTo设置的贡献路径,每个贡献都会得到它所属的整个家族模型。但我不需要所有这些数据,我只需要每个贡献的家族表中的一个字段(不是id,而是不同的字段)。

以下是我的型号和资源控制器:

class Family extends Eloquent {
    protected $table = 'families';
    // relationships
    public function contributions() {
        return $this->hasMany('Contribution');
    }
}
class Contribution extends Eloquent {
    protected $table = 'contributions';
    // relationships
    public function family() {
        return $this->belongsTo('Family');
    }
    public function other_field() {
        return $this->belongsTo('Family')->select('other_field');
    }   
}
class ContributionController extends BaseController {
    public function index()
    {
        // works - but returns the entire family with every contribution
        $contributions = Contribution::with('family')->get();
        // returns other_field == null with every contribution
        $contributions = Contribution::with('other_field')->get();
        return Response::json($contributions->toArray(),
            200);
    }

从belongsTo关系中选择此字段会出错吗?

如果使用急切加载,则可以对关系使用查询约束。

Family::with(['contributions', function($query)
{
    $query->select('column');
}])->get();