laravel - 如何连接两个表并从 Laravel 的第一个表中获取 id
问题描述
我正在尝试加入表格posts
并tags
获取表格的 ID posts
,但是这段代码给了我tags
表格的 ID(11),但帖子 ID 是 15。
$posts = Post::leftJoin('tags', 'tags.post_id', '=', 'posts.id')
->where('tags.slug', $slug)->get();
dd($posts);
表格标签
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('post_id');
$table->string('tag');
$table->string('slug');
$table->integer('views')->nullable();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
表帖
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('admin_id')->nullable();
$table->string('title');
$table->string('slug')->unique();
$table->integer('views')->default(0);
$table->longText('content');
$table->text('meta_keywords')->nullable();
$table->text('meta_description')->nullable();
$table->enum('is_home', ['0', '1',])->default('1');
$table->enum('is_featured', ['0', '1',])->default('0');
$table->enum('is_slider', ['0', '1',])->default('0');
$table->integer('slider_order')->default(0);
$table->enum('type', ['Article', 'Video']);
$table->enum('status', ['Visible', 'Invisible', 'Draft', 'Pending']);
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('admin_id')->references('id')->on('admins');
$table->timestamps();
});
型号标签
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $fillable = [
'post_id', 'tag', 'slug',
];
public $timestamps = false;
}
模特帖子
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function tags()
{
return $this->hasMany(Tag::class);
}
}
解决方案
尝试
$posts = Post::leftJoin('tags', 'tags.post_id', '=', 'posts.id')
->select('tags.id as tag_id','posts.*')
->where('tags.slug','=', $slug)
->get();
现在$posts->id
将上桌id
。将是表。posts
$posts->tag_id
id
tags
推荐阅读
- visual-studio-code - 通过键入键盘快捷键反向查找 VSCode 命令
- php - 用于非 WordPress Twig 的 Timber 插件
- c++ - 有没有办法 ⎕NA 在 dyalog APL 中导入 dll 导出的 C++ 类?
- c# - 使用 ASP.NET MVC 和 OWIN 在 Xamarin.Forms 上缺少外部 cookie
- python - 如何将 shapely.Polygon 对象列表保存为一个 geojson 文件?
- android - Android 警报管理器崩溃 Flutter 应用程序 - 运行时异常、线程/异步问题
- excel - 如果满足条件(黄色突出显示)并粘贴到另一个单元格中,如何复制单元格?
- javascript - 如何在堆叠卡片上包含导航箭头和进度条
- angularjs - 为 Webpack 4 加载 AngularJS 模板的正确方法?
- node.js - 返回错误的意图应该是buy_food not hello