【问题标题】:How to get the primary key of the Users table to comments table foreign key using eloquent in Laravel 7 or 8如何在 Laravel 7 或 8 中使用 eloquent 获取用户表的主键到评论表的外键
【发布时间】:2021-06-15 02:34:22
【问题描述】:

我想将 users 表获取或加入到我的 cmets 表中。但我不知道该怎么做 我使用 hasMany 将所有 cmets 表添加到 posts 。我想加入 users 表到

这是我的模特帖子

namespace App\Models;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    class Posts extends Model
    {
        use HasFactory;
        public function comments(){
            return $this->hasMany(Comments::class,'posts_id');
        }
    }

这是我的 PostsController 我使用 hasManypostscmets

namespace App\Http\Controllers;
use App\Models\Posts;
class UserController extends Controller
{
    public function index(){
        return Posts::with('comments')->get();
        return view('welcome',['authors'=>$authors]);
    }
}

我的 PostsController 的输出使用 hasMany

   [
    {
    "id": 1,
    "post": "im in relationship now",
    "comments": [
            {
            "posts_id": 1,
            "comments_id": 1,
            "users_id": 1,
            "comments": "sweet"
            },
            {
            "posts_id": 1,
            "comments_id": 2,
            "users_id": 2,
            "comments": "grats"
            },
            {
            "posts_id": 1,
            "comments_id": 3,
            "users_id": 3,
            "comments": "wow"
            },
            {
            "posts_id": 1,
            "comments_id": 4,
            "users_id": 4,
            "comments": "grats dudes"
            }
        ]
    },
    {
    "id": 2,
    "post": "im graduate now",
    "comments": [
            {
            "posts_id": 2,
            "comments_id": 5,
            "users_id": 5,
            "comments": "stay strong"
            },
            {
            "posts_id": 2,
            "comments_id": 6,
            "users_id": 6,
            "comments": "sweets"
            },
            {
            "posts_id": 2,
            "comments_id": 7,
            "users_id": 7,
            "comments": "ayiee"
            }
        ]
    }
]

在输出中,您看到 cmets 有一个 users_id,我想加入 users 表以获取该表的信息,例如名称和用户名

【问题讨论】:

    标签: laravel eloquent has-many-through has-many


    【解决方案1】:

    在 Comment.php 模型中添加这个关系

    public function user() {
            return $this->belongsTo( User::class );
        }
    

    在视图中的 cmets 的 for 循环中

    {{$comments->user->name}}
    

    【讨论】:

      【解决方案2】:

      我已经解决了

      return $posts = Posts::with(['user', //users who created and posted
              'comments' => function($user) {
                  $user->with('users'); //users who commented 
       }])->get();
      

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 2021-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-29
        • 2014-01-14
        • 2021-09-08
        • 1970-01-01
        相关资源
        最近更新 更多