标签: eloquent

使用“JSON”列的 Laravel 5 关系

是否可以使用 Eloquent 在 Laravel 5 中创建外键存在于列中字段中的关系JSON

如果是的话,怎么会这样呢?

示例:我有一个chats带有数据类型participantIds列的表JSONJSON数据的格式如下所示:

{"creator": "1", "recipient": "2"}
Run Code Online (Sandbox Code Playgroud)

我想users使用这些字段加入表来获取聊天的参与者。我怎么做?

database json eloquent laravel-5 php-7

0
推荐指数
1
解决办法
2342
查看次数

Laravel Nova:将字段动态绑定到模型上的 JSON 属性

拉拉维尔·诺瓦

对于特定项目,我想结合使用 Nova Resource UI 的强大功能和更灵活的数据模型。具体来说,我希望能够将字段添加到存储在 JSON 数据库字段中而不是表中的属性的资源中。

规格:

数据库模型:报价(含迁移)

public function up()
{
    Schema::create('quotations', function(Blueprint $table)
    {
        $table->bigInteger('id', true);
        $table->timestamps();
        $table->string('client_name', 100)->nullable();
        $table->string('client_surname', 100)->nullable();
        $table->string('status', 10)->nullable()->default('NEW');
        $table->text('data')->nullable();
    });
}
Run Code Online (Sandbox Code Playgroud)

新星资源

因此,我可以定义一个“正常”NOVA 资源,并在 App\Nova\Quotation 中定义以下字段(*忽略状态):

public function fields(Request $request)
{
    return [
        Text::make('Client Name')->sortable(),
        Text::make('Client Surname')->sortable(),


    ];
}
Run Code Online (Sandbox Code Playgroud)

现在我的“愿望”是达到这种效果,使用不存在的“bindTo”方法来说明我想要实现的目标

public function fields(Request $request)
{
    return [
        Text::make('Client Name')->sortable(),
        Text::make('Client Surname')->sortable(),

        //Fields bound into the JSON data property  
        Text::make('Client Id')->bindTo('data.client_id),
        Date::make('Client Date Of Birth')->bindTo('data.client_date_of_birth),

        //etc       


    ];
}
Run Code Online (Sandbox Code Playgroud)

因此,当保存报价模型时,client_name 和 …

laravel eloquent laravel-nova

0
推荐指数
1
解决办法
4398
查看次数

Eloquent - 检测多列重复数据

我有一个有 3 列的表id, sub_id, name。这是一个相当大的表,并且有一些重复项。

检测重复项以便将其删除的最佳方法是什么?

我尝试了这个,但它返回了所有内容(我猜认为 ids 使它们变得不唯一)

$collection = \App\MyModel::all();
$colUnique = $collection->unique(['name', 'sub_id']);
$dupes = $collection->diff($colUnique);
Run Code Online (Sandbox Code Playgroud)

name我想要获得具有相同和 的模型sub_id

id    sub_id   name
1       2      John
2       2      John   <- duplicate
3       2      Robin  <- unique
Run Code Online (Sandbox Code Playgroud)

query-builder laravel eloquent laravel-collection

0
推荐指数
1
解决办法
5088
查看次数

Laravel - 返回控制器中参数的相关模型

我有以下路线:

Route::get('/api/products/{product}', 'ProductController@get');
Run Code Online (Sandbox Code Playgroud)

我的产品模型如下所示:

class Product extends Model
{
    public function ingredients()
    {
        return $this->belongsToMany(Ingredient::class)->withPivot('value');
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,方法是:

public function get(Product $product)
{
    return $product;
}
Run Code Online (Sandbox Code Playgroud)

Product这仅以JSON 形式返回对象的属性。我还想返回相关成分和数据透视表值(就像使用该with方法一样),以及可能的其他相关模型。

return $product->with('ingredients')创建所有产品的集合,因此这实际上不起作用,我必须通过产品 ID 再次过滤它。显然,我可以自己构建 JSON,但如果我想要包含多个相关模型,这就变得很乏味。有没有一种简单的方法可以实现这一点?

routes laravel eloquent

0
推荐指数
1
解决办法
1465
查看次数

如何转化雄辩关系对象?

我们有以下型号 -

邮政

----------------------------------------------
| id | title | text | creator | status | etc |
----------------------------------------------
|    |       |      |         |        |     |
----------------------------------------------

creator -> belongsTo User

group -> belongsTo group
Run Code Online (Sandbox Code Playgroud)

用户

posts -> hasMany Posts

avatar -> hasOne Media
Run Code Online (Sandbox Code Playgroud)

媒体

user -> belongsTo User
Run Code Online (Sandbox Code Playgroud)

团体

post - belongsTo Post
Run Code Online (Sandbox Code Playgroud)

当我使用 eloquent 获取帖子时,我可以使用转换函数来转换帖子属性,但无法转换帖子集合中的关系。

$posts = Post::where('status', 'active')
            ->with(['creator.avatar','group'])
            ->get();

$posts->transform(function($post) {
    $post->title = 'Transformed'; // works
    $post->creator->avatar = ['path'=>'/avatar/','file_name'=>'a.png']; // does not work
});
Run Code Online (Sandbox Code Playgroud)

laravel eloquent

0
推荐指数
1
解决办法
2012
查看次数

Laravel Eloquent GroupBy KeyBy

我有一个语言表,其中包含以下列。

  • 国家代码
  • 代码
  • 价值

该表包含与我的应用程序的不同部分相关的各种代码。例如,主屏幕可能会显示“欢迎”,因此该短语的代码是“欢迎”。我会在表中存储 3 个不同语言的变体,并设置国家/地区代码。

示例数据集

country_code  |  code     |  value
------------------------------------------------
EN            |  welcome  |  Welcome
FR            |  welcome  |  Bienvenue
DE            |  welcome  |  herzlich willkommen
Run Code Online (Sandbox Code Playgroud)

我正在尝试运行一个雄辩的查询,该查询将返回如下结果:其想法是将结果按country_code分组,然后将每个结果集的键作为代码列。

{
  "EN": [
      "welcome": {
        "country_code": "EN",
        "value": "Welcome",
        "code": "welcome"
      },
      "goodbye": {
        "country_code": "EN",
        "value": "Goodbye",
        "code": "goodbye"
      }
  ],
  "FR": [
      "welcome": {
        "country_code": "FR",
        "value": "Bienvenue",
        "code": "welcome"
      },
      "goodbye": {
        "country_code": "FR",
        "value": "Au revoir",
        "code": "goodbye"
      }
  ],
  "DE": [
      "welcome": {
        "country_code": …
Run Code Online (Sandbox Code Playgroud)

php laravel eloquent

0
推荐指数
1
解决办法
1788
查看次数

Laravel 条件 API 资源即使不需要也执行所有功能?

所以我有一个 Laravel API 资源,它返回模型的标准数据库信息。但是,在某些情况下,我需要此资源来呈现一些触发复杂/缓慢查询的数据。

当我需要这些数据时,我不介意花费更长的时间,但由于大多数用例不需要它,所以我想使用$this->when()资源中的方法有条件地呈现它。

class SomeResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'created_at' => $this->created_at,

            //The "slow_query()" should not be executed
            'slow_result' =>  $this->when(false, $this->slow_query()),
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,即使条件when为假,慢速查询仍然会执行,尽管结果从未显示并且查询毫无用处。

如何slow_query()在不需要时阻止该方法运行?

这是 Laravel 5.8 上的

laravel eloquent

0
推荐指数
1
解决办法
539
查看次数

Laravel 中的 create() 和 insert() 有什么区别

create()Laravel 中和之间的确切区别是什么insert()?我浏览了视频和博客,但没有找到任何令人满意的答案。

laravel eloquent

0
推荐指数
1
解决办法
1万
查看次数

如何使用 Postgres jsonb '?' Laravel 中的运算符是否支持索引?

我正在尝试使用 jsonb 存在运算符 '?' 在 Laravel 的查询生成器中,并让它使用索引,但我遇到了一些问题。

示例查询

DB::table('table_name')->whereRaw("jsonb_column ? 'key'")->get();

样本索引

CREATE INDEX ON table_name USING GIN(jsonb_column jsonb_ops)

主要问题似乎是“?” 保留用于参数替换,因此该查询返回语法错误。我找到了几种解决此问题的方法,但每种方法都不是完整的解决方案。

  1. 使用 '??' (逃避的方法?) ->whereRaw("jsonb_column ?? 'key'")

    • 不适用于查询生成器。回报SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: jsonb ?? unknown
    • 适用于原始查询,例如DB::select("SELECT * FROM table_name WHERE jsonb_column ?? 'key'"),但我需要它与查询生成器一起使用。
  2. 使用命名函数/为运算符创建别名

    • '?' 转换为函数 - jsonb_exists(jsonb, text)
      • ->whereRaw("jsonb_exists(jsonb_column, 'key')")
    • CREATE OPERATOR @-> ( PROCEDURE = jsonb_exists, LEFTARG = jsonb, RIGHTARG = text );
      • ->whereRaw("jsonb_column @-> 'key'")
    • 这些解决方案都“有效”......但它们不使用索引

现在我正在研究CREATE OPERATOR CLASS …

php postgresql json laravel eloquent

0
推荐指数
1
解决办法
1760
查看次数

Laravel - 雄辩的数组位置

我试图根据文档执行此查询,但它返回错误array_key_exists(): The first argument should be either a string or an integer

https://laravel.com/docs/5.8/queries#where-clauses

 $imagessize = $galleryObj->photos->where([
                ['gallery_id','=', $gallery->id],
                ['delete','=',0],
            ])->sum('filesize');
Run Code Online (Sandbox Code Playgroud)

arrays where-clause laravel eloquent

0
推荐指数
1
解决办法
2万
查看次数