簡體   English   中英

屬於 laravel 5.8 中的關系

[英]belongsTo relationship in laravel 5.8

我想在帖子和用戶之間建立關系,以便能夠通過這種方式獲取所有帖子 $user->posts() 並通過這種方式獲取用戶 $post->user()

我做了belongsTo function,但我需要一種方法,所以當我得到用戶時,當我得到我使用的帖子時,我也能以某種方式找到他的所有帖子 \App\Post::find(1)->user()->name 它返回沒有什么

發布 Model

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

后數據庫結構

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();
        });

用戶 Model 沒有任何內容,而不是 laravel 默認值,因為用戶沒有引用帖子的列

用戶數據庫結構為 Laravel 默認

Foreach 代碼:

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

我希望它能夠獲得用戶名,但它沒有..

使用hasMany關系。

在用戶 model 內:

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

現在,您可以獲取所有用戶帖子:

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

Docs about有很多關系

希望能幫助到你。

在用戶 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');
    }
}

在用戶 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');
    }
}

現在您可以通過App\User::find(id)->posts訪問用戶的帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM