【发布时间】:2019-09-11 13:09:21
【问题描述】:
我正在使用 laravel-eloquent 并希望返回一个连接多个表的集合。目前,我使用查询构建器连接方法来执行此操作,但我想保持在 eloquent 范围内。我的意思是,我已经定义了我所有的关系,为什么我要一直用外键编写连接?
例如,如果我这样定义我的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comments');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
并且想要返回所有带有用户名的 cmets,现在我会这样写:
DB::table('users')->select('users.name', 'comments.body')
->join('comments', 'users.id', '=', 'user_id')
->get();
我试过写
$users = new 'App\User';
$users->with('comments')
->select('name', 'comments.body');
但它没有用。我需要定义一个新的集合吗?如果我这样做,我最终会得到很多很多的收藏......
【问题讨论】:
-
->with('cmets') 究竟是如何不起作用的?在第二个示例中创建新用户而在第一个示例中创建用户的背后有什么原因吗?如果您正在创建新用户。它不会有任何 cmets。