Laravel 从国外查询不同的值 table
Laravel query distinct values from Foreign table
我有一个 laravel 项目 post s table 并制作 table。我已经在 make 和 post table 之间建立了关系。
帖子 table 包含 make_id。
我想查询并获取所有 post 的所有独特品牌。我做了一个查询并获得了唯一性 make_id's.But 无法获得唯一性 make_names。我在这里错过了什么?
后模型:
<?php
namespace App;
use App\Post;
use App\Make;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $dates = ['status_change'];
public function make_rel()
{
return $this->belongsTo(Make::class, 'make_id' ,'id','make_logo');
}
}
我的查询:
$makesforsearch = Post::select('make_id')->distinct()->pluck('make_id');
我得到的结果
Collection {#511 ▼
#items: array:5 [▼
0 => "9"
1 => "1"
2 => "5"
3 => "6"
4 => "11"
]
}
这个结果是正确的。但不是 9、1、5、6 和 11。我应该得到他们的品牌名称,即 BMW、Harley、Roayl、Indian 和 Honda。下面是 make table 的屏幕截图。
我错过了什么?如何解决?
好吧,您确实使用了 ::select('make_id')
,然后是 ->pluck('make_id')
。
为什么您会惊讶于您的结果只包含您采摘的内容?
尝试 Posts::all()->get()->make_rel()->distinct()
或相同的代码,但使用 make_rel
而不是 make_rel()
您需要 Make
的东西。所以从Make
开始。
并仅过滤具有 post 的品牌,使用 whereHas()
$uniqueMakeNames = Make::whereHas('posts')->pluck('make_name')->unique();
确保您已在 Make
模型上定义 postst()
关系。
class Make extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
我有一个 laravel 项目 post s table 并制作 table。我已经在 make 和 post table 之间建立了关系。 帖子 table 包含 make_id。 我想查询并获取所有 post 的所有独特品牌。我做了一个查询并获得了唯一性 make_id's.But 无法获得唯一性 make_names。我在这里错过了什么?
后模型:
<?php
namespace App;
use App\Post;
use App\Make;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $dates = ['status_change'];
public function make_rel()
{
return $this->belongsTo(Make::class, 'make_id' ,'id','make_logo');
}
}
我的查询:
$makesforsearch = Post::select('make_id')->distinct()->pluck('make_id');
我得到的结果
Collection {#511 ▼
#items: array:5 [▼
0 => "9"
1 => "1"
2 => "5"
3 => "6"
4 => "11"
]
}
这个结果是正确的。但不是 9、1、5、6 和 11。我应该得到他们的品牌名称,即 BMW、Harley、Roayl、Indian 和 Honda。下面是 make table 的屏幕截图。
我错过了什么?如何解决?
好吧,您确实使用了 ::select('make_id')
,然后是 ->pluck('make_id')
。
为什么您会惊讶于您的结果只包含您采摘的内容?
尝试 Posts::all()->get()->make_rel()->distinct()
或相同的代码,但使用 make_rel
而不是 make_rel()
您需要 Make
的东西。所以从Make
开始。
并仅过滤具有 post 的品牌,使用 whereHas()
$uniqueMakeNames = Make::whereHas('posts')->pluck('make_name')->unique();
确保您已在 Make
模型上定义 postst()
关系。
class Make extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}