doutui8842 2015-12-12 13:08
浏览 67
已采纳

如何根据数据透视表中的属性计算数据量?

i am a beginner in Laravel 5, and im trying to develop a blog, let's say i have an Article model which has many to many relation with Tag model.

This is the Article model:

<?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();
    }

}

This is the Tag model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model {

    public function articles() {
        return $this->belongsToMany('App\Article')->withTimestamps();
    }

}

Here is the migration for the Articles table and the Article_Tag pivot table:

<?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');
    }

}

This is the migration for the tags table:

<?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');
    }

}

So lets say, i have 3 tags in my database, "lifestyle", "social", "economy".

Assume that an article is created with tag "lifestyle", then in the ArticleController, in the store function, i want the count attribute on the "lifestyle" tag to be set to the amount of the articles in the database (in this case, it will count from the pivot table) which has the "lifestyle" tag, using the count() function.

If the tag_id is in the articles table, i can do it like this in the controller:

$article = new Article($request->all());
$article->save();

foreach($article->tags as $tag) {
    $tag->count = Article::where('tag_id', $request->tag_id)->count();
    $tag->save();
}

But in this case, the where function defers to a column in the pivot table, and i had no idea how to do it.

Any solution for my beginner's error? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongmo9996 2015-12-12 13:27
    关注

    You can easily count articles that belong to given tag by calling:

    $tag->count = $tag->articles()->count();
    $tag->save();
    

    The above will run 2 SQL queries - one to do the count and one to update the tag. You could also try the following, that would do a single query:

    Tag::whereId($tag->id)->increment('count');
    

    This will run a single SQL UPDATE query:

    UPDATE `tags` SET `count` = `count` + 1 WHERE `id` = {$tag->id}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题