Laravel : Eloquent 关系无效。无法在视图中显示关系

Laravel : Eloquent Relationships not work. Cannot show relationships in view

我已经在模型中设置 Eloquent 关系后无法在视图中显示关系。

模型中:Art_obj

class Art_obj extends Model
{
    protected $table = 'art_objs';
    protected $fillable = ['Id_no','Artist','Year','Title','Description','Origin','Epoch','Picture','Type_of_art'];

    public function Painting(){
        return $this->hasOne(Painting::class,'Id_no');
    }

}

模特中:绘画

class Painting extends Model
{

    protected $table = 'paintings';
    protected $fillable = ['art_obj_Id_no','Paint_type','Drawn_on','Style'];

    public function Art_obj(){
        return $this->belongsTo(Art_obj::class,'Id_no');
    }

}

在绘画控制器中

public function index()
    {
        $paintings = Painting::with('Art_obj');
        return view('ArtObj.Painting', compact('paintings'));
    }

在Painting.blade.php

            <table class="table table-bordered table-striped"> 
                <tr> 
                    <th>Title</th>
                    <th>Paint type</th> 
                    <th>Drawn on</th>
                    <th>Style</th>
                    </tr> 
                        @foreach($paintings as $row) 
                    <tr> 
                    <td>{{$row->Art_obj->Title}}</td>
                    <td>{{$row['Paint_type']}}</td> 
                    <td>{{$row['Drawn_on']}}</td> 
                    <td>{{$row['Style']}}</td> 
                </tr> 
                @endforeach 
            </table> 

它没有任何现场表演。 enter image description here

如果您不使用 id 作为模型的主键,则需要在模型中设置主键 属性:

protected $primaryKey = 'Id_no';

Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.

此外,关系必须设置正确的外键和所有者键:

public function Art_obj(){
    return $this->belongsTo(Art_obj::class,'Id_no', 'art_obj_Id_no');
}

然后检索数据:

$paintings = Painting::with('Art_obj')->get();

您还应该在尝试访问之前检查关系是否存在:

@foreach($paintings as $row) 
<tr> 
   @if (!is_null($row->Art_obj))
   <td>{{$row->Art_obj->Title}}</td>
   @else
   <td>No Title</td>
   @endif
   <td>{{$row->Paint_type}}</td> 
   <td>{{$row->Drawn_on}}</td> 
   <td>{{$row->Style}}</td> 
</tr> 
@endforeach 

您还没有获取数据。将您的查询更改为:

$paintings = Painting::with('Art_obj')->get();