Laravel-5.8: Попытка получить свойство 'display_name' необъекта (представление: D: \ xampp \ htdocs \ MyProject \ resources \ views \ pages \ index.blade.php) - PullRequest
0 голосов
/ 20 мая 2019

Я получаю сообщение об ошибке «Попытка получить свойство display_name не-объекта» в Laravel при попытке оценить данные из модели категории.

У меня 2 модели: почта и категория; для которых у меня есть соответствующие таблицы:
Posts('id', 'title', 'body', 'cover_image')
и
Categories('id', 'display_name','name', 'key).

Сводная таблица: столбец категории

Это мой пост Модель:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //Table Name
    protected $table = 'posts';


    //Model Relationships

    public function tag(){
        return $this->belongsToMany('App\Tag', 'id');
    }

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

Вот моя категория Модель:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

//Model Relationships

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

}

Кроме того, это мой PagesController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PagesController extends Controller
{
    public function index()
    {
        if ( !is_null(Post::class) ) {    
            $posts = Post::latest()->with('category')->paginate(5);

            return view('pages.index')->with(['posts' => $posts]);
        }
        else {
            return view('pages.empty');
        }
    }

А это мой блейд-файл:

@if(count($posts) > 0)
   @foreach($posts as $post)
      <span> <i class="fa fa-folder-open"></i> {{ $post->category->display_name }} </span>
   @endforeach
@endif

ОБНОВЛЕНИЕ

Это мои миграции: Таблица сообщений:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug')->nullable();
            $table->mediumText('body');
            $table->string('cover_image')->default('noimage.jpg')->nullable();
            $table->integer('user_id');
            $table->timestamps();
            $table->integer('category_id')->unsigned()->nullable();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

И моя таблица категорий:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name');
            $table->string('description')->nullable();
            $table->string('password')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Предполагаемый результат - получить display_name из таблицы категорий и отобразить их в виде списка. Это ошибка, которую я продолжаю получать

Попытка получить свойство 'display_name' не-объекта (представление: D: \ xampp \ htdocs \ MyProject \ resources \ views \ pages \ index.blade.php)

Я пытался назвать это так:

<span> <i class="fa fa-folder-open"></i> {{ $post->category()->display_name }} </span>

Но это также не работает.


EDIT:

После сброса переменной $ post в Контроллере:

Post {#331 ▼
  #table: "posts"
  #fillable: array:7 [▼
    0 => "id"
    1 => "title"
    2 => "slug"
    3 => "body"
    4 => "cover_image"
    5 => "user_id"
    6 => "category_id"
  ]
  +primaryKey: "id"
  +timestamps: true
  #connection: "mysql"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:9 [▼
    "id" => 1
    "title" => "This is a Base Announcement"
    "slug" => null
    "body" => "Please feel free to delete this announcement and create a new one afterwards."
    "cover_image" => "noimage.jpg"
    "user_id" => 1
    "created_at" => "2019-05-20 14:22:45"
    "updated_at" => "2019-05-20 14:22:45"
    "category_id" => null
  ]
  #original: array:9 [▼
    "id" => 1
    "title" => "This is a Base Announcement"
    "slug" => null
    "body" => "Please feel free to delete this announcement and create a new one afterwards."
    "cover_image" => "noimage.jpg"
    "user_id" => 1
    "created_at" => "2019-05-20 14:22:45"
    "updated_at" => "2019-05-20 14:22:45"
    "category_id" => null
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}

Ответы [ 2 ]

0 голосов
/ 20 мая 2019

Я думаю, вы допустили ошибку в методе post() в вашей модели Category.Попробуйте изменить этот метод следующим образом:

Категория Модель:

public function post() 
{
    return $this->hasMany('App\Post', 'id');
}

Источник: Красноречивые отношения один-ко-многим

0 голосов
/ 20 мая 2019

Проблема в том, что вы не сохраняете CATEGORY_ID в своей таблице сообщений, хорошо сохраняете идентификатор категории и пробуете так:

Обновление модели POST:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //Table Name
    protected $table = 'posts';

    // Setup fields of table "posts"
    protected $fillable = ['id', 'title', 'body', 'cover_image','category_id'];

    //Model Relationships
    public function tag(){
        return $this->belongsToMany('App\Tag', 'id');
    }
    // Relation category to foreign key 
    public function category() {
        return $this->belongsTo('App\Category','category_id');
    }
}

Категория Модель

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

    // Setup fields of table "category"
    protected $fillable = ['id', 'display_name', 'name', 'key'];

    //Model Relationships
    public function posts() 
    {
        return $this->hasMany('App\Post');
    }

}

Посмотреть

@if(count($posts) > 0)
   @foreach($posts as $post)
      <span> <i class="fa fa-folder-open"></i> {{ $post->category->display_name }} </span>
   @endforeach
@endif

Миграционные посты - внешний ключ category_id

Schema::create('posts', function (Blueprint $table) {

            // Your other fields.....

            // You must setup category like this
            $table->integer('category_id')->nullable()->unsigned();
            $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

Контроллер

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PagesController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        if (!empty($posts)) {  

            // Please let me know this test
            dd($posts[0]->category->display_name);
            return view('pages.index', ['posts' => $posts]);
        }
        else {
            return view('pages.empty');
        }
    }
...