【问题标题】:Laravel eloquent - making query with optional value key parameters with relationshipLaravel eloquent - 使用带有关系的可选值键参数进行查询
【发布时间】:2017-07-01 11:09:47
【问题描述】:

我需要使用可选参数数组进行查询,可能如下所示:

array:3 [
  "parent" => "prosjektsamarbeidets"
  "category" => "article"
  "slug" => "prosjektsamarbeidets-verdi"
]

它总是有一个 slug 参数,但其他参数在数组中是可选的。 有了这个参数,我需要在模型Content 中进行查询,其中category 的关系在这种情况下指的是模型Taxonomy,如下所示:

public function taxonomies()
{
    return $this->morphToMany('App\ContentTaxonomy', 'taggable');
}

如果存在,parent 键值是内容表中记录的名称,其中包含以下列:

id | cms_id | title | slug | excerpt | body | parent_id  

在我得到content by slug 后,我该如何进行这样的查询?

$post = Content::where('slug',$arguments['slug'])->get();

if (array_key_exists('parent', $arguments)) {
      //do further query by parent name
}

if (array_key_exists('category', $arguments)) {
      //do further query by category
}

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    你应该试试:

    public function taxonomies()
    {
        return $this->morphToMany('App\ContentTaxonomy', 'taggable')->withPivot('additional_attribute', 'additional_attribute');;
    }
    

    然后,您可以通过以下方式访问这些变量:

    foreach ($shop->taxonomies as $taxonomy)
    {
        echo $taxonomy->pivot->additional_attribute;
    }
    

    或者你的意思是:

    $post = Content::taxonomies()->where('slug',$arguments['slug'])->get();
    

    让我知道你是不是这个意思?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 2013-10-03
      • 2017-07-19
      • 2016-12-01
      • 2021-03-21
      相关资源
      最近更新 更多