belongsTo Laravel关系

时间:2018-04-23 10:56:56

标签: php laravel

我的belongsTo关系具有以下结构:

public function author() {
    return $this->belongsTo('App\User', 'author_id', 'id');
}

它产生以下查询(执行$message->author()->getResults()->toSql()时):

select * from "users" where "users"."id" is null and "users"."deleted_at" is null limit 1

$message包含有效的Message个实例,其author_id已设置且相关的User已存在。

编辑1:正如@Jonas Staudenmeir指出的那样,我的原始代码并不是我在代码中实际拥有的代码。但是,下面的评论仍然存在,因为在输入问题时我只是将params错配了。我编辑了代码,准确地表达了项目中的内容。

编辑2:包含消息模型。 "附件()"顺便说一句,关系很好。

class Message extends Model
{
    use \Eloquent\Dialect\Json;
    use \Spatie\Macroable\Macroable;
    use SoftDeletes;

    /**
     * @var array
     */
    protected $guarded = [
        'id', 'created_at', 'updated_at', 'deleted_at',
    ];

    /**
     * @var array
     */
    protected $jsonColumns = [];

    public function author()
    {
        return $this->belongsTo('App\User', 'author_id', 'id');
    }

    public function attachments()
    {
        return $this->hasMany('App\File', 'file_id');
    }
}

1 个答案:

答案 0 :(得分:1)

您必须更改参数顺序:

public function author() {
    return $this->belongsTo('App\User', 'author_id', 'id');
}