简体   繁体   中英

Creating a hasMany Relation in Laravel 5

I'm trying to create a Tag/Content structure. A content object is assigned to a Tag object and Tag objects can be assigned to many Contents. I'm getting an error:

Trying to get property 'name' of non-object (View: D:\\laragon\\www\\project1\\resources\\views\\contents\\show.blade.php)

These are my Models:

Content:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Content extends Model {
    public function tag() {
        return $this->belongsTo('App\Tag');
    }
}

Tag:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Tag extends Model {
    public function contents() {
        return $this->hasMany('App\Content');
    }
}

ContentController:

/**
* Display the specified resource.
*
* @param  int  $id
* @return \Illuminate\Http\Response
*/
public function show($id) {
    $content = Content::find($id);
    return View('contents.show')
                ->with('content', $content);
}

show.blade.php:

@extends('layouts.app')
@section('content')
<div class="container">
    <h1> {{ $content->tag->name }} - {{ $content->title }} </h1>
    <div class="row">
        <div class="col-lg-12">
            Title: {{ $content->title }}
        </div>
        <div class="col-lg-12">
            Body: {{ $content->body }}
        </div>
        <div class="col-lg-12">
            Tag: {{ $content->tag }}
        </div>
        <hr />
        <div class="col-lg-12">
            {!! link_to('contents', 'Back', ['class' => 'btn btn-danger']) !!}
        </div>
    </div>
</div>
@endsection

The error I'm getting is from h1 tag: {{ $content->tag->name }}

Any Ideas? Thanks in advance :)

参考模型内的表名

protected $table ="<table_name>"

您必须在调用"$content->tag->name"之前检查"$content->tag"是否有效。

The problem is that in the table contents should have tag_id, but you can solve it in this way in the Content model

class Content extends Model {
    public function tag() {
        return $this->belongsTo('App\Tag');
    }
}

class Tag extends Model {
    public function contents() {
        return $this->hasMany('App\Content',  'tag');
    }
}

This was the solution:

Change column name tag to tag_id and change return $this->belongsTo('App\\Tag'); to return $this->belongsTo('App\\Tag','tag_id');

The final code was:

Content Model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Content extends Model {
    public function tag() {
        return $this->belongsTo('App\Tag','tag_id');
    }
}

Tag Model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Tag extends Model {
    public function contents() {
        return $this->hasMany('App\Content');
    }
}

Thank you all for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM