首页 > 解决方案 > 在视图 laravel 中传递具有关系的数据

问题描述

如果我有这个模型关系

索赔模型

   class Claims extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'dossier',
        'date_cla',
    ];

    public function refunds()
        {
            return $this->hasMany(Refunds::class);
        }               
}

退款模式

class Refunds extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'date_ref',
        'status_ref',
    ];

    public function services()
        {
            return $this->belongsToMany(Services::class)->withPivot(['services_id','services_amount','services_status']);
        }       

    public function claims()
        {
            return $this->belongsTo(Claims::class,'claims_id');
        }           

}

服务模式

   class Services extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'code',
        'name',
    ];

    public function refunds()
    {
        return $this->belongsToMany(Refunds::class);
    }

}

在我的控制器中这个方法

if ($request->ajax()) {
        $dossier = request('dossier');
        $claim = Claims::with('refunds')
        ->where('dossier', '=', $dossier)->first();

        $

        $view = view('pages.modify', compact('claim'));
        $sections = $view->renderSections()['table'];
        return $sections;
    }

如何在 Controller 中插入 Refunds 和 Service 之间的关系以使用枢轴(service_amount 在 Refunds-Services 表中)

<li>- {{ $item->pivot->services_amount }}</li>

因为现在在视图中看不到这种关系 Thx

标签: laravelrelationshiplaravel-blade

解决方案


您可以使用嵌套急切加载

$claim = Claims::with('refunds.services')
    ->where('dossier', '=', $dossier)->first();

根据文档

要急切加载嵌套关系,您可以使用“点”语法。例如,让我们在一个 Eloquent 语句中急切地加载本书的所有作者和作者的所有个人联系人:

$books = App\Book::with('author.contacts')->get();


推荐阅读