【问题标题】:How to create a Laravel Eloquent Model from Collection?如何从 Collection 创建一个 Laravel Eloquent 模型?
【发布时间】:2021-09-07 11:14:30
【问题描述】:

为了将 Algolia 搜索与 Airtable 数据一起使用,在 Laravel 应用程序中,我认为需要使用我检索到的数据创建一个 Eloquent 模型,然后才能使用 Laravel Scout。

我可以使用从 Airtable 检索到的 Collection 数据作为没有 DB 的模型吗?

【问题讨论】:

    标签: php laravel collections model


    【解决方案1】:

    为此有一个hydrate 方法:

    YourModel::hydrate($collections->toArray())
    

    但如果你只有一个对象,你就可以

    $res = new YourModel($your_object)
    

    或者你甚至可以使用fill

    (new YourModel())->fill($your_obj)
    

    显然,除非您不调用 saveupdate 或类似的东西,laravel 尝试将该模型保存在数据库中,否则您是安全的(也许考虑从模型中“禁用”它们,这样如果你不小心调用了这些方法,什么都不会发生)

    【讨论】:

    • 太棒了,谢谢 - 这个模型可以与 Laravel Scout 交互好吗?
    • @MikeThrussell 我会说是的,至少如果你从 laravel 扩展 Model 我不明白为什么会有问题
    • 引发 MySql 错误:php artisan scout:import "App\Models\AirtableThing" Illuminate\Database\QueryException SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (SQL: select * from airtable_things order by id asc limit 500)
    • @MikeThrussell 你说你没有数据库,而scout:import 确实:If you are installing Scout into an existing project, you may already have database records you need to import into your indexes... 所以要么你有数据库,要么你不想使用导入...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2015-03-25
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多