渴望加载关系时没有结果,但是关系存在

塞巴斯蒂安·斯托尔(Sebastian Stoll):

我有2个使用UUID的模型。我创建了一个名为Model的抽象类,该类扩展了\ Illuminate \ Database \ Eloquent \ Model,并设置了以下默认值:

public $incrementing = false;

我的问题是使用-> with('lines')时,lines关系不会返回任何结果,但是如果我不使用-> with('lines'),它不会返回结果:

示例1(失败):

$lines_count = Order::whereId($id)->with('lines')->first()->lines->count(); // 0

示例2(WORKS):

$lines_count = Order::whereId($id)->first()->lines->count(); // 2

范例3:

$quotation = Order::whereId($quotation_id)
    ->with('lines')
    ->withCount('lines')
    ->firstOrFail();
dd($quotation->lines_count.' - '.$quotation->lines); // Returns "2 - 0"

关系:

订购

class Order extends Model {
    public function lines()
    {
        return $this->hasMany(OrderLine::class, 'order_id', 'id');
    }
}

订单行

class OrderLine extends Model {
    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }
}

先感谢您!我真的很努力

apokryfos:

Laravel从版本6开始,在连接字段为整数时(这是默认假设),进行了一些急切的加载优化。

但是,如果您有UUID(是字符串),则需要在模型中使用以下命令指定此名称:

public $incrementing = false;
protected $keyType = 'string';

文档中的更多详细信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章