Php Larvel如何循环控制器中的数组并组合关系

Php Larvel如何循环控制器中的数组并组合关系,php,laravel,Php,Laravel,在我的laravel-应用程序中,我有一个blogs-和一个author-表。在索引页面上,您可以看到所有已发布的博客文章,我希望显示作者姓名。所以我试着这样做: public function index() { $blogs = Blog::where("publishes_on", "<=", Carbon::now()) ->orderBy('publishes_on', 'desc') ->published()

在我的
laravel
-应用程序中,我有一个
blogs
-和一个
author
-表。在索引页面上,您可以看到所有已发布的博客文章,我希望显示作者姓名。所以我试着这样做:

public function index()
{

    $blogs = Blog::where("publishes_on", "<=", Carbon::now())
        ->orderBy('publishes_on', 'desc')
        ->published()
        ->get();

    foreach ($blogs as $blog) {
        $author = Author::where('id', $blog->author_id)->get();
    }

    return view('app.blog.index', compact('blogs', 'author'));
}
公共功能索引()
{

$blogs=Blog::where(“发布”,“无需使用
foreach
循环

Blog::with('author')->其中([…]`
在你看来

$blog->author->name
确保将
author()
定义为
Blog
model:

e、 g

class博客{
函数作者(){
返回$this->belongsTo(Author::class);
}
}

无需使用
foreach
循环

Blog::with('author')->其中([…]`
在你看来

$blog->author->name
确保将
author()
定义为
Blog
model:

e、 g

class博客{
函数作者(){
返回$this->belongsTo(Author::class);
}
}

在博客模型中添加作者关系

public function author()
{
   return $this->belongsTo(Author::class);
}
内部控制器

$blogs = Blog::where("publishes_on", "<=", Carbon::now())
    ->orderBy('publishes_on', 'desc')
    ->published()
    ->with('author:id,name')
    ->get();

在博客模型中添加
作者
关系

public function author()
{
   return $this->belongsTo(Author::class);
}
内部控制器

$blogs = Blog::where("publishes_on", "<=", Carbon::now())
    ->orderBy('publishes_on', 'desc')
    ->published()
    ->with('author:id,name')
    ->get();

你必须连接一个
博客属于作者
关系并通过该关系获取作者的详细信息你必须连接一个
博客属于作者
关系并通过该关系获取作者的详细信息在博客模型中添加belongsTo关系,以防OP遗漏这太棒了!非常感谢!!:-)在博客模型中添加belongsTo关系,以防万一OP遗漏了这太棒了!非常感谢!!:-)这也是一个很好的答案!这也是一个很好的答案!