【问题标题】:How to join two tables and get id from first table in Laravel如何连接两个表并从 Laravel 的第一个表中获取 id
【发布时间】:2019-10-08 03:03:55
【问题描述】:

我正在尝试加入poststags 表并获取posts 表的ID,但此代码给我tags 表的ID (11),但帖子ID 是15。

result

$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);
    }
}

【问题讨论】:

  • 你可以试试这个Post::select('posts.*', 'tags.*')->leftJoin('tags', function($leftJoin) { $leftJoin->on('tags.post_id', '=', 'posts.id'); })->get();
  • 不工作!给出相同的结果。
  • 你能发布你的toSql()结果吗?
  • 检查我已经包含在帖子中的图片。
  • 我的意思是sql字符串结果。不是 $posts 结果

标签: laravel


【解决方案1】:

试试

 $posts = Post::leftJoin('tags', 'tags.post_id', '=', 'posts.id')
           ->select('tags.id as tag_id','posts.*')
           ->where('tags.slug','=', $slug)
           ->get();

现在$posts->id 将是idposts 表。$posts->tag_id 将是idtags 表。

【讨论】:

  • 我现在没有足够的声誉来做这个,我稍后会标记它。
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 2021-08-23
  • 1970-01-01
  • 2019-08-09
  • 2021-04-28
相关资源
最近更新 更多