【问题标题】:How to use "with" in laravel?如何在 laravel 中使用“with”?
【发布时间】:2017-09-09 00:41:43
【问题描述】:

我使用这个包:https://github.com/jenssegers/laravel-mongodb

我的 laravel 雄辩是这样的:

$query = Product::where('store_id', $id)       
                ->with('store')
                ->get();

我的产品型号是这样的:

public function store()
{
    return $this->belongsTo(Store::class, 'store_id', '_id');
}

当我执行dd($query)时,结果是这样的:

我在数据库中看到,数据存在

我试着改变成这样:

return $this->belongsTo(Store::class, 'store_id', 'id');

都一样

我该如何解决这个问题?

【问题讨论】:

  • 请详细说明您的问题。
  • 您真的确定,您在 stores 表中有一个具有该特定 id 的 Store 吗?这似乎更有可能是您的数据库完整性被破坏

标签: php mongodb laravel laravel-5.3 laravel-eloquent


【解决方案1】:

试试

public function store()
{
    return $this->belongsTo(Store::class, null,  'store_id', '_id');
}

同时添加

protected $primaryKey = 'your_primary_key';

到您的模型。

希望这会有所帮助。 :)

【讨论】:

    【解决方案2】:

    我认为您可以通过以下方式解决您的问题:

      $query = Product::with('store')->where('store_id', $id)       
                ->get();
    

    在模型中:

    public function store()
    {
        return $this->belongsTo('App\Store','store_id', '_id');
    }
    

    然后在你的命令提示符下运行这个命令:'composer dump-autoload'。

    谢谢.....

    【讨论】:

    • with() 有什么用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2018-07-11
    • 2019-10-02
    • 1970-01-01
    • 2022-10-23
    • 2022-07-22
    • 2016-01-03
    相关资源
    最近更新 更多