簡體   English   中英

Laravel 上的關系

[英]Relationships on Laravel

我正在使用 laravel 5.2 修復平台我嘗試了很多東西,但我不能讓它工作:/希望有人能幫助我

這是我的維修台

Schema::create('repairs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('brand');
        $table->foreign('brand')->references('id')->on('brands');
        $table->integer('equipment');
        $table->foreign('equipment')->references('id')->on('equips');
        $table->string('model');
        $table->string('description');
        $table->integer('status');
        $table->foreign('status')->references('id')->on('statuses');
        $table->string('code');
        $table->string('notes');
        $table->timestamps();

    });

然后我有控制器

public function index()
{
  $repairs = repair::all();
  return view('repair.index_repair',compact('repairs'));
}

這是我的模型

class Repair extends Model

{

protected $fillable = ['brand','equipment','model','description','status','code'];

public function brand ()
{
    return $this->belongsTo('App\brands', 'id');
}

當我嘗試打印這樣的品牌名稱時

@foreach($repairs as $repair)
                <tr>
                  <th>{{$repair->brand->name}}</th>
                  <th>{{$repair->equipment}}</th>
                  <th>{{$repair->model}}</th>
                  <th>{{$repair->description}}</th>
                  <th>{{$repair->status}}</th>
                  <th>{{$repair->code}}</th>
                  <th>
                    {!! Form::open(array('route'=>['repair.destroy',$repair->id],'method'=>'DELETE')) !!}
                    {{ link_to_route('repair.edit','Edit',[$repair->id],['class'=>'btn btn-primary']) }}
                    |
                    {!! Form::button('Delete',['class'=>'btn btn-danger','type'=>'submit']) !!}
                    {!! Form::close() !!}
                  </th>

                </tr>

                @endforeach

我有這個錯誤“試圖獲取非對象的屬性”。 這是一個非常常見的錯誤,我看到一些有同樣問題的人的話題,我嘗試使用他們的解決方案但不起作用。 我不知道該怎么辦了.. 任何人都可以幫助我嗎?

謝謝

更新

現在我有這個:

控制器:

public function index()
{
  $repairs = repair::with('brands')->get();
  return view('repair.index_repair',compact('repairs'));
}

維修型號:

class Repair extends Model

{

protected $fillable = ['brand','equipment','model','description','status','code'];

public function brands ()
{
    return $this->hasOne('App\brands','brand','id');
}

}

品牌型號:

    class brands extends Model
{

protected $fillable = ['name'];

    public function repair () {

      return $this->belongsTo('App\Repair','brand','id');

    }


}

它給了我這個錯誤“Connection.php 第 729 行中的 QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'brands.brand' in 'where 子句'(SQL:從brands中選擇 * brands在哪里brandsbrand在( 1, 2))"

我嘗試了一切......:/

您應該在brand_id表中使用brand_id 而不是brand來自動找出您的密鑰。 如果你想使用brand ,你應該告訴 Laravel 它是品牌外鍵:

public function brand ()
{
    return $this->belongsTo('App\brands', 'brand', 'id');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM