检索关系 Laravel 的记录

时间:2021-05-02 17:01:17

标签: php laravel eloquent laravel-7 eloquent-relationship

当用户登录时,我需要显示已在主题中发布的帖子。用户可以关注许多主题。 1 个主题有很多帖子,1 个主题有很多用户通过数据透视表“topic_user”“注册”

我想知道关于这个的查询..

我有这 4 个模型:

1 - 普通用户

然后:

class Post extends Model
{
    use SoftDeletes;
    //
    protected $fillable = ['title','content', 'creator_id','topic_id','flag_id','deleted_at',"created_at"];
    
    public function topic(){
        return $this->belongsTo(Topic::class);
    }
}
class Topic extends Model
{
    use SoftDeletes;
    protected $fillable = ['name','description','active','creator_id','nsfw','type_id','formal_name','theme','joined_community'];

    public function posts(){
        return $this->hasMany(Post::class);
    }
    public function enrolled(){
        return $this->belongsToMany(User::class,'topic_user');
    }
}
class UserOnTopic extends Model
{
    protected $fillable = ["user_id","topic_id"];
    protected $table = "topic_user";
}

1 个答案:

答案 0 :(得分:0)

您已经建立了关系。因此,您可以通过主题和帖子查询用户:

PS C:\Users\Administrator> $menuObjts.MENUS.PSobject.Properties
ReferencedMemberName : Length
ConversionType       : 
MemberType           : AliasProperty
TypeNameOfValue      : System.Int32
IsSettable           : False
IsGettable           : True
Value                : 17
Name                 : Count
IsInstance           : False

MemberType      : Property
Value           : 17
IsSettable      : False
IsGettable      : True
TypeNameOfValue : System.Int32
Name            : Length
IsInstance      : True
...
MemberType      : Property
Value           : {@{MENU=typeInstallation; PARENT=LICENSE; MENU_GRP=0; MENU_IDX=0; MENU_OFFSET=-1; MENU_SEL-TYPE=; nrElems=13;FUNCTION=f1; info=Windows-Defender has to be uninstalled, before installing an other anti-virus program;status=-1; SEL=0; RESTART=1; STOP=},
@{MENU=activate; PARENT=; MENU_GRP=0; MENU_IDX=1; MENU_OFFSET=-1; MENU_SEL-TYPE=; nrElems=13; FUNCTION=f2; info=Windows has to be upgraded if working with an EVALUATION prod key;status=-1; SEL=0; RESTART=0; STOP=},
@{MENU=NAME; PARENT=HOST; MENU_GRP=0; MENU_IDX=2; MENU_OFFSET=-1;MENU_SEL-TYPE=; nrElems=13; FUNCTION=f3; info=F-SEC has to be configured as an isolated machine on the CSI server;status=-1; SEL=0; RESTART=0; STOP=},
@{MENU=IP; PARENT=; MENU_GRP=0; MENU_IDX=3; MENU_OFFSET=-1; MENU_SEL-TYPE=;nrElems=13; FUNCTION=f4; info=disable default Windows NTP service; status=-1; SEL=0; RESTART=1; STOP=}...}
IsSettable      : False
IsGettable      : True
TypeNameOfValue : System.Object
Name            : SyncRoot
IsInstance      : True
...

这行代码返回第一个用户,以及属于他关注的主题的所有帖子。

您可以使用以下方式在前端显示他的帖子:

$user_posts = User::with('topics', 'topics.posts')->first();