donglipi4495 2017-01-31 10:02
浏览 89

Laravel Model关系在单个循环中获取parent> child-> field

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');
 }
}

`i want to fetch parent and child model relationships but in a single loop for both parent and child table because maatwebsite-excel export is not working according to its defined scenario AND CHILD MODEL

namespace App;

use Illuminate\Database\Eloquent\Model;

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

and i want simply without nested loop

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

here is the child table structure

  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();

    });
}
  • 写回答

1条回答 默认 最新

  • dongmu5815 2017-01-31 10:44
    关注

    In your parent model you can define child relation.

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

    The pluck method retrieves all of the collection values for a given key. https://laravel.com/docs/5.1/collections#method-pluck

    评论

报告相同问题?