简体   繁体   English

Laravel雄辩的一对一反演返回空

[英]Laravel eloquent inverse one to many returns empty

I have following MySQL table structure: 我有以下MySQL表结构:

posts table: posts表:

posts: {id(PK), title, content, slug, date, writer_id, created_at, updated_at}

writers table: writers表:

writers: {id(PK), name, type, created_at, updated_at}

Migration classes in database/migrations directory: database/migrations目录中的迁移类:

posts table: 帖子表:

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->longText('content');
            $table->string('slug');
            $table->date('date');
            $table->date('modified_date');
            $table->integer('publish');
            $table->integer('trash');
            $table->integer('wid');
            $table->timestamps();
        });
    }

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

Changed the type of column: 更改了列的类型:

class RenamePostColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function ($table) {
            $table->longText('content')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function ($table) {
            $table->longText('content')->change();
        });
    }
}

Renamed a column: 重命名列:

class RenamePostColumnWid extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function ($table) {
            $table->renameColumn('wid', 'writer_id')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function ($table) {
            $table->renameColumn('writer_id', 'wid')->change();
        });
    }
}

writers table: 作家表:

class CreateWritersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('writers', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('name');
            $table->string('type');
        });
    }

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

Following are my modals in app directory: 以下是我在app目录中的模态:

Post.php: Post.php:

class Post extends Model
{
    public function writer()
    {
        return $this->belongsTo(Writer::class);
    }
}

Writer.php: Writer.php:

class Writer extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

Now I have created a repository class in app/Repositories directory. 现在,我在app/Repositories目录中创建了一个存储库类。

PostRepository.php: PostRepository.php:

class PostRepository
{
    public function forSingle($slug)
    {
        return Post::whereSlug($slug)->get();
    }
}

I debugged above query with: 我用以下命令调试了上面的查询:

return Post::whereSlug($slug)->toSql();

It returns the following query: 它返回以下查询:

select * from `posts` where `slug` = ?

My routes are in routes/web.php file. 我的路线在routes/web.php文件中。

web.php: web.php:

Route::get('/post/{slug}', 'PostController@single');

Finally I have my controller in app/Http/Controllers directory. 最后,我将控制器放在app/Http/Controllers目录中。

PostController.php: PostController.php:

use App\Repositories\PostRepository;

class PostController extends Controller
{
    protected $post;

    function __construct(PostRepository $post)
    {
        $this->post = $post;
    }

    public function single($slug)
    {
        return view('single', [
            'post' => $this->post->forSingle($slug)
        ]);
    }
}

I have rendered a view file as follows: 我渲染了一个视图文件,如下所示:

single.blade.php single.blade.php

@if (count($post) > 0)
    @foreach ($post as $blog)
        <h3><a href="#">{{$blog->title}}</a></h3>
        <p>{!!$blog->content!!}</p>
        @foreach($blog->writer as $writer)
            <span>{{$writer->name}}</span>
        @endforeach
    @endforeach
@endif

Here is my problem. 这是我的问题。 Everything works fine until I add 一切正常,直到我添加

@foreach($blog->writer as $writer)
    <span>{{$writer->name}}</span>
@endforeach

This section gives me error saying: 这部分给我错误提示:

Trying to get property of non-object (View:\\resources\\views\\single.blade.php) 尝试获取非对象的属性(视图:\\ resources \\ views \\ single.blade.php)

I have printed the $blog in view by {{$blog}} . 我已经在{{$blog}}视图中打印了$ blog。 It does not return any writer attribute. 它不返回任何writer属性。 Can you help me with this? 你能帮我吗?

PS: I have not defined primary key foreign key relationships in MySQL database tables. PS:我尚未在MySQL数据库表中定义主键外键关系。

When it is inverse one to many eloquent, we need to explicitly tell that we need the other table data. 当它是一对多的雄辩的逆时,我们需要明确地告诉我们我们需要其他表数据。 Changing following in the PostRepository.php fixed the issue. PostRepository.php中更改以下内容解决了该问题。

class PostRepository
{
    public function forSingle($slug)
    {
        return Post::whereSlug($slug)->with('writer')->get();
    }
}

You have to define foreign key or index 您必须定义外键或索引

In my projects, I use index relation 在我的项目中,我使用索引关系

so what you have to do is to add index relation in writer_id like this 所以你要做的是像这样在writer_id中添加索引关系

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->longText('content');
        $table->string('slug');
        $table->date('date');
        $table->date('modified_date');
        $table->integer('publish');
        $table->integer('trash');
        $table->integer('wid')->unsigned()->index(); // add this
        $table->timestamps();
    });
}

Please try the previous 请尝试以前的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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