如何在Laravel 6中表达hasMany关系

问题描述 投票:0回答:1

[我正在使用Laravel 6,我想讲一下Layanan模型和Objek模型之间的hasMany关系

这是我的模特

Layanan模型

class Layanan extends Model
{
    protected $fillable=[
        'nama_layanan'
    ];

    protected $primaryKey = 'layanans_id';

    public function objeks() {
        return $this->hasMany(Objek::class);
    }
}

Objek模型

class Objek extends Model
{
    protected $fillable=[
        'layanan_id', 'tipe_objeks'
    ];
    protected $primaryKey = 'objeks_id';

    public function layanan() {
        return $this->belongsTo(Layanan::class);
    }
}

这是我的控制器

ObjekController.php

use App\Objek;
use Illuminate\Http\Request;

class ObjekController extends Controller
{

public function object(){
    $objek = \App\Objek::all();
    return view ('pages.alat.object.object')->with('data',$objek);
}

这是我的foreach

@foreach ($data as $item)                   
                @foreach ($item->layanan as $layanan)
                <tr>
                  <td>{!! $item->objeks_id !!}</td>
                  <td>
                    {!! $layanan->layanan_id !!},
                  </td>
                  <td>{!! $item->tipe_objeks !!}</td>
                  <td>{!! $item->created_at->format('d/m/Y') !!}</td>
                  <td>{!! $item->updated_at->format('d/m/Y') !!}</td>
                </tr>
@endforeach
@endforeach

我得到错误

为foreach()提供了无效的参数

我做错了什么?有时,它说“ layanan”不是对象

laravel eloquent laravel-6
1个回答
0
投票
class Objek extends Model { protected $fillable=[ 'layanan_id', 'tipe_objeks' ]; protected $primaryKey = 'objeks_id'; public function layanan() { return $this->hasMany(Layanan::class); } }
如果您放ObjekhasManylayanan

然后只有u可以循环1行Objek

例如$data = Objek::find(1(=);

foreach($data as $layanan)

热门问题
推荐问题
最新问题