【问题标题】:Laravel - One to Many relationship is not working one wayLaravel - 一对多关系不是以一种方式工作
【发布时间】:2016-07-06 01:44:36
【问题描述】:

我在 Laravel 中有一个问题,在一对多关系中,如果从一侧(“hasMany”的一侧)使用它会返回 null,但反过来(“belongsTo”的一侧)会返回包含对象。在我的例子中,一个类别可以有很多线程,并且所有线程都属于一个类别。

下面是相关代码:

类别:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public $timestamps = false;
    protected $table = 'categories';

    public function threads() {
        $this->hasMany('App\Thread', 'category_id');
    }
}

线程:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

我试图在哪里得到它:

Thread::with('category')->get();
$latestThread = dd(Category::find(1)->threads());

每个的表结构如下: 分类:

id, name, description

线程:

id, name, user_id, category_id

(如果您想知道的话, dd 会输出 null)。如果您还需要什么,请询问!

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您错过了线程函数中的 return 关键字

    public function threads() {
        return $this->hasMany('App\Thread', 'category_id');
    }
    

    【讨论】:

    • 我觉得会是这样的傻事,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2019-06-17
    • 2016-09-03
    • 2013-07-08
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多