Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel Elount中的嵌套数据结构_Php_Mysql_Laravel_Eloquent - Fatal编程技术网

Php Laravel Elount中的嵌套数据结构

Php Laravel Elount中的嵌套数据结构,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我在Laravel/MySQL中有一个users_表和users_tweets_表。我想用这个结构返回响应数据: [ { id:1, name:'Johne', tweets:[ { id:1, content:"something" }, { id:2, content"something else" } ] }, { id:2, name:'Jennifer', tweets:[ { id:1, content:"something"

我在Laravel/MySQL中有一个users_表和users_tweets_表。我想用这个结构返回响应数据:

[
{
id:1,
name:'Johne',
tweets:[
{
id:1,
content:"something"
},
{
id:2,
content"something else"
}
]
},
{
id:2,
name:'Jennifer',
tweets:[
{
id:1,
content:"something"
},
{
id:2,
content"something else"
}
]
},
]
我试过这个,但不好:

  $list = User::all();
    $list = $list->
    skip($skip)->
    take($take);
    foreach ($list as $user)
    {

        $user['tweets']=UserTweet::where('user_id',$user['id'])->get();
    }
    return response(['message' => 'The list of users', 'data' => $list], 200);

我怎样才能用雄辩和innerjoin做到这一点?

你应该在你的模型之间建立关系

在用户模型中:

  public function tweets()
    {
        return $this->hasMany(UserTweet::class, 'user_id');
    }
在UserTweet模型中:

public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }
现在你可以告诉你的亲戚:

$list = User::with('tweets')->all();

更多关于一对多关系的信息,请参见

您尝试了什么?添加一些代码非常好,我有另一个问题:我想把表名从tweets改为评论。我怎么做你可以在这里看到答案,这是非常好的一个:不,我不想真的改变表名,如果我想把返回数据中的关键字从tweets改为评论!只需重新命名关系。。。公共函数comments(){……},然后$list=User::with('comments')->all();