如何访问元素口才查询

时间:2019-01-01 15:40:32

标签: laravel eloquent

属性模型

class PostProperty extends Model
{
    protected $table = 'post_properties';

    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

发布模型

class Post extends Model
{
    public function postproperties()
    {
        return $this->hasMany('App\PostProperty');
    }
}

表格

Click here Click here

示例输出

$ pv这是我的数组:example('car','25','foo')

查询

$posts = Post::with('postproperties')
    ->where('type_id', '=', $type)
    ->where(function ($q) use ($title, $pv) {
        $q->orWhere('title', 'like', '%' . $title . '%')
            ->orwhere(function ($qq) use ($pv) {
                for ($i = 0; $i < count($pv); $i++)
                    $qq->orwhere('property_value', 'like', '%' . $pv[$i] . '%');
            });
    })
    ->get();

我需要访问postproperties的元素以放入查询条件。

2 个答案:

答案 0 :(得分:1)

        $posts = DB::table('posts')
        ->leftJoin('post_properties','posts.id','=','post_properties.post_id')
        ->select('posts.*')
        ->where('posts.type_id','=',$type)
       ->where('posts.verified_at','!=',null)
        ->where(function($q)use($title,$pv){
            $q->orwhere('posts.title','like','%'.$title.'%');
            for ($i=0;$i<count($pv);$i++)
                $q->orwhere('post_properties.property_value','like','%'.$pv[$i].'%');
        })
        ->distinct('posts.id');

更好

答案 1 :(得分:0)

解决

        $posts = Post::where('type_id','=',$type)
        ->leftJoin('post_properties','posts.id','=','post_properties.post_id')
        ->where(function($q)use($title,$pv){
            $q->orwhere('title','like','%'.$title.'%');
            for ($i=0;$i<count($pv);$i++)
                $q->orwhere('property_value','like','%'.$pv[$i].'%');
        })
        ->groupBy('id')
        ->get();