Laravel:如何将一种模型的一个变量传递给不同的查询以查看以及如何在视图中访问它

问题描述 投票:0回答:1

我正在学习laravel。我一度感到困惑。

我有一个模型Trader,它与另外两个模型AgriculturalProduceMarketCommetteeCategoryMaster具有一对一的关系。traders表具有apmc_idcategory_id作为外键。现在,我想在一张表格中显示traders_nameapmc_branch_namecategory_name

交易者模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Trader extends Model
{
       /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'traders';

    // primary key
   public $primaryKey = 'traders_id';

    //timestamps
    public $timestamps = true;

      /**
       * Attributes that should be mass-assignable.
       *
       * @var array
       */
      protected $fillable = [
          'apmc_id','category_id', 'traders_name', 'traders_address','traders_contact_number'
      ];


    /**
 * Get the apmc that has the trader.
 */
public function apmc()
{
    return $this->belongsTo('App\AgriculturalProduceMarketCommettee', 'apmc_id');
}


    /**
 * Get the category that has the trader.
 */
public function categoryMaster()
{
    return $this->belongsTo('App\CategoryMaster', 'category_id');
}

}

TraderController

public function index()
    {
        $traders = Trader::all();
        $traderApmc = Trader::with('apmc')->get();
        $traderCategory = Trader::with('categoryMaster')->get();
        return view('traders.tradersDetails', compact('traders','traderApmc','traderCategory'));
    }

tradersDetails.blade.php:视图

 <table id="example1" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                          <th>Trader Name</th>
                          <th>APMC Branch Name</th>
                          <th>Category Name</th>

                        </tr>
                        </thead>
                        <tbody>
                          @if(count($traders) >= 1)
                          @foreach ($traders as $trader)

                        <tr>
                            <td> {{$trader->traders_name}} </td>
                            <td> {{$traderApmc->apmc->apmc_branch_name}} </td>  
                            <td> {{$traderCategory->categoryMaster->category_name}} </td> 
                        </tr>
                        @endforeach 
                        @else
                        <p>No records found!</p>
                        @endif
                        </tbody>
                     </table>

现在TraderController中,我正在为一个模型'traders','traderApmc','traderCategory'传递3个不同的变量Trader以查看3个不同查询的tradersDetails。但鉴于我使用变量的方式会给我类似集合>>的错误

Facade\Ignition\Exceptions\ViewException Property [apmc] does not exist on this collection instance.

我应该如何传递这些变量并在视图中访问它?请指导。预先感谢。

我正在学习laravel。我一度感到困惑。我有一个模型交易者,该模型交易者与其他两个模型AgricultureProduceMarketCommettee和CategoryMaster具有一对一的关系。商人...

php laravel model-view-controller
1个回答
0
投票

不是使用3个变量,而是可以组合使用:

© www.soinside.com 2019 - 2024. All rights reserved.