-2
namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model    
{
 protected $fillable = ['department_id'];
 protected $guarded = array('*');

 public function bank()
 {
    return $this->hasMany('App\Bank');
 }
}

`我想获取父子模型关系,但在父子表的单个循环中,因为 maatwebsite-excel 导出无法根据其定义的场景和子模型工作

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bank extends Model
{
 public function employee()
 {
    return $this->belongsTo('App\Employee');
 }
}

我只想没有嵌套循环

public function downloadExcel(Employee $employee , $Type)
{
   $data = $employee->with('bank', 'certificate')->get();
   foreach ($data as $parentkey => $emp) {
       $emp->childtable->columname;
  }
}

这是子表结构

  public function up()
{
    Schema::create('bank', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('emp_id');
        $table->string('bankname');
        $table->string('branchname');
        $table->string('branchcode');
        $table->string('acc_code');
        $table->string('branchcity');
        $table->string('acc_type');
        $table->string('cert_created_by');
        $table->string('cert_updated_by');
        $table->foreign('emp_id')->references('id')->on('employees');
        $table->timestamps();

    });
}
4

1 回答 1

0

在您的父模型中,您可以定义子关系。

public function downloadExcel(Employee $employee , $Type)
{
   $data = Employee::with('bank', 'certificate')->get();
   foreach ($data as $parentkey => $emp)
   {
       $child =  $emp->bank->pluck('bankname');
   }
}

pluck 方法检索给定键的所有集合值。 https://laravel.com/docs/5.1/collections#method-pluck

于 2017-01-31T10:44:55.640 回答