我是Laravel 5的初学者,我试图开发一个博客,假设我有一个与Tag模型有很多关系的文章模型。
这是文章模型:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $fillable = [
'name',
'description'
];
public function tags() {
return $this->belongsToMany('App\Tag')->withTimestamps();
}
}
这是Tag模型:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
public function articles() {
return $this->belongsToMany('App\Article')->withTimestamps();
}
}
以下是Articles表和Article_Tag数据透视表的迁移:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('name')->unique();
$table->text('description');
$table->timestamps();
});
Schema::create('article_tag', function(Blueprint $table)
{
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('article_tag');
Schema::drop('articles');
}
}
这是标签表的迁移:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function(Blueprint $table)
{
$table->increments('id');
$table->string('name')->unique();
$table->integer('count')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tags');
}
}
让我们说,我的数据库中有3个标签,“生活方式”,“社交”,“经济”。
假设使用标签“lifestyle”创建了一篇文章,然后在ArticleController中,在store函数中,我希望将“lifestyle”标签上的count属性设置为数据库中文章的数量(在这种情况下,它将使用count()函数计算具有“lifestyle”标签的数据透视表。
如果tag_id在articles表中,我可以在控制器中这样做:
$article = new Article($request->all());
$article->save();
foreach($article->tags as $tag) {
$tag->count = Article::where('tag_id', $request->tag_id)->count();
$tag->save();
}
但在这种情况下,where函数会延伸到数据透视表中的一列,而我不知道该怎么做。
我的初学者错误的任何解决方案?提前谢谢。
答案 0 :(得分:0)
您可以通过调用以下内容轻松统计属于给定标记的文章:
$tag->count = $tag->articles()->count();
$tag->save();
上面将运行2个SQL查询 - 一个用于计数,另一个用于更新标记。您还可以尝试以下操作,即执行单个查询:
Tag::whereId($tag->id)->increment('count');
这将运行一个 SQL UPDATE 查询:
UPDATE `tags` SET `count` = `count` + 1 WHERE `id` = {$tag->id}