简体   繁体   English

属于 laravel 5.8 中的关系

[英]belongsTo relationship in laravel 5.8

I want to make a relation between post and user to be able to get all posts by this way $user->posts() and to get user by this way $post->user()我想在帖子和用户之间建立关系,以便能够通过这种方式获取所有帖子 $user->posts() 并通过这种方式获取用户 $post->user()

I made belongsTo function but i need a way so when i get the user i can find all his posts somehow also when i get the post i used \App\Post::find(1)->user()->name it return nothing我做了belongsTo function,但我需要一种方法,所以当我得到用户时,当我得到我使用的帖子时,我也能以某种方式找到他的所有帖子 \App\Post::find(1)->user()->name 它返回没有什么

Post Model发布 Model

class Post extends Model
{
    public function user() {
        return $this->belongsTo('App\User',null,'userid');
    }
}

Post DB Structure后数据库结构

Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->longText('body');
            $table->string('thumbnail');
            $table->integer('views');
            $table->integer('likes');
            $table->bigInteger('userid');
            $table->integer('categoryid');
            $table->timestamps();
        });

User Model has nothing in it rather than laravel defaults because user has no columns that refer to posts用户 Model 没有任何内容,而不是 laravel 默认值,因为用户没有引用帖子的列

User DB Structure is Laravel Default用户数据库结构为 Laravel 默认

Foreach code: Foreach 代码:

@foreach(\App\Post::find(4)->user() as $user)
            <p>{{$user->name}}</p>
@endforeach

i expected it to get the user name but it didn't..我希望它能够获得用户名,但它没有..

Use the hasMany relationship.使用hasMany关系。

Within user model:在用户 model 内:

public function posts()
{
    return $this->hasMany(Post::class, 'userid', 'id');
}

Now, you are able to get all user posts:现在,您可以获取所有用户帖子:

$posts = User::find($someId)->posts()->get();
//or
$posts = User::find($someId)->posts;

Docs about has many relationship Docs about有很多关系

Hope it helps.希望能帮助到你。

In User model在用户 model

<?php

namespace App;

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

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In User model在用户 model

<?php

namespace App;

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

class User extends Model
{
    /**
     * Get the posts for the user.
     */
    public function comments()
    {
        return $this->hasMany('App\Post');
    }
}

Now you can access posts of user as App\User::find(id)->posts现在您可以通过App\User::find(id)->posts访问用户的帖子

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

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