首页 > 解决方案 > Laravel 7关系查询数据不起作用

问题描述

我想通过员工查询公司名称。为什么没有得到任何结果?它不会给出任何错误。

公司模式

    public function employees() {
        return $this->hasMany(Employees::class);
    }

员工模型

   
    public function companies() {
        return $this->belongsTo(Companies::class);
    }

员工控制器

     public function createIndex() {

        $employees = Employees::all();

        return view('employees.create', [
            'employees' => $employees
        ]);
    }

我想查询的地方

            <div class="form-group">
                <label for="company">Company: </label>
                <select name="company" class="form-control">
                @foreach($employees as $employe)
                    <option selected>Choose...</option>

                    @foreach($employe->companies as $company)
                        <option id="company">{{ $company->name }}</option>
                    @endforeach
                @endforeach
                </select>
            </div>

这是表的迁移

        Schema::create('companies', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('logo');
            $table->string('website');
            $table->timestamps();
        });

        Schema::create('employees', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('fname');
            $table->string('lname');
            $table->string('email');
            $table->string('phone');
            $table->bigInteger('companies_id')->unsigned();
            $table->timestamps();
            $table->foreign('companies_id')->references('id')->on('companies')
                      ->onDelete('cascade');
        });

标签: phplaravel

解决方案


请提供您关系的外键...

 public function companies()
 { return $this->belongsTo(Companies::class,'companies_id'); }

这种关系意味着该员工只有一家公司(属于一家公司)

所以你不能迭代它!

在这一行:

@foreach($employe->companies as $company)
                    <option id="company">{{ $company->name }}</option>
                @endforeach

employee->companies 将只返回一个对象.. 如果您想将所有公司显示为选项,请传递 $allCompany ,例如:

 public function createIndex() {

        $employees = Employees::all();
   $compnanies = Companies::all();
        return view('employees.create', [
            'employees' => $employees,'compnanies'=> $compnanies
        ]);
    }

然后你可以在你的视图中迭代 $compnanies


推荐阅读