Laravel 5.错误:我的模型有破坏和一个关系。

时间:2016-07-10 12:17:16

标签: laravel

存在问题,因为已添加了transhed,与tablerelation冲突。

型号:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

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

控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Category;
use App\Models\Post;
use Session;
use Auth;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = new Post();
        // $allPosts = $posts::onlyTrashed()->get();
        // $allPosts = $posts::withTrashed()->get();
        $allPosts = $posts::all();
        $postDeleted = $posts::onlyTrashed()->count();
        return view('admin.post.index', ['posts' => $allPosts, 'postDeleted' => $postDeleted]);
    }

...

查看:

        @foreach ($posts as $post)
        <tr class="table-pages-list-item">
          <td><input type="checkbox"></td>
          <td>{{ $post->h1 }}</td>
          <td>{{ $post->url }}</td>
          <td>{{ $post->category->h1 }}</td>
          <td>
            @if ($post->published)
                        <span class="label label-success">Да</span> 
                    @else
                        <span class="label label-danger">Нет</span>
                    @endif
          </td>
          <td>{{$post->updated_at}}</td>
          <td>
            <a href="#"type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="left" title="Редактировать">
              <i class="fa fa-edit"></i>
            </a>
            <a href="#" target="_blank" type="button" class="btn btn-success" data-toggle="tooltip" data-placement="top" title="Просмотреть">
              <i class="fa fa-external-link"></i>
            </a>
            <form action="{{ action('PostController@destroy', ['id' => $post->id]) }}" method="post">
              <input type="hidden" name="_token" value="{{ csrf_token() }}">
              <input type="hidden" name="_method" value="DELETE">
              <button type="submit" class="btn btn-danger" data-toggle="tooltip" data-placement="right" title="В корзину">
                <i class="fa fa-trash-o"></i>
              </button>
            </form>
          </td>
        </tr>
        @endforeach

此处出现错误<td>{{ $post->category->h1 }}</td>

尝试获取非对象的属性(查看:C:\ OpenServer \ domains \ laravel \ resources \ views \ admin \ post \ index.blade.php)

2 个答案:

答案 0 :(得分:0)

因为您将外键命名为category_id,就像约定一样,我认为您应该像这样定义雄辩的关系

public function category() {
    return $this->hasOne('App\Models\Category');
}

你应该在Model.php文件上看到如何定义一对一关系的hasOne方法。

答案 1 :(得分:0)

请检查您的类别表有哪些字段! 它是否包含'h1'字段,您正在访问'h1'键,但可能不在桌面