User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'user';
protected $primaryKey = 'id';
public $timestamps = false;
public function comments(){
return $this->hasOne('App\Models\Comment', 'uid', 'uid');
}
}
Comment.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $primaryKey = 'id';
public $timestamps = false;
public function comments(){
return $this->hasMany('App\Models\User', 'uid', 'uid');
}
}
我想在Test控制器中使用User模型中comments方法的数据 应该怎么使用呢?
use App\Models\User;
class TestController extends Controller{
public function test(){
}
}
这是典型的一对多模型关联: Eloquent 关联:一对多
从你的源码来看,你的映射关系是错的,一个用户肯定会发表多个评论,所以在 User model 中应该是用 hasMany,
而对于 Comment 模型,每个评论只属于一个用户
拿到用户的所有评论写法如下:
如果你拿到了一条评论数据,要获取到该评论的用户模型,应该是
其实在官方文档中已经说的比较清楚了,请认真仔细阅读文档。