Json: как добавить среднее значение, чтобы получить среднее значение

У меня есть функция, которая отображает список tarificationtaches, я хотел бы добавить среднее значение, чтобы получить среднее значение moyenne_avis для «techniciens» из таблиц avis_intervention, где «interval.technicien_id» = «tarificationtaches.techncien_id», это моя схема.

taches_table

public function up()
{
    Schema::create('taches', function (Blueprint $table) {
        $table->increments('id');
        $table->string('libelle_tache');
        $table->float('Tarif', 8,2)->nullable();
        $table->integer('metier_id')->unsigned();
        $table->foreign('metier_id')->references('id')->on('metiers');
        $table->datetime('deleted_at')->nullable();
        $table->timestamps();
    });
}

tarificationtaches_tables

Schema::create('tarificationtaches', function (Blueprint $table) {
    $table->increments('id');
    $table->float('tarif', 8,2);
    $table->integer('tache_id')->unsigned();
    $table->foreign('tache_id')->references('id')->on('taches');
    $table->integer('technicien_id')->unsigned();
    $table->foreign('technicien_id')->references('id')->on('techniciens');
    $table->datetime('deleted_at')->nullable();
    $table->timestamps();
});

techniciens_tables

    Schema::create('techniciens', function (Blueprint $table) {
    $table->increments('id');
    $table->boolean('actif')->default(1);
    $table->float('moyenne_avis')->nullable();
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->datetime('deleted_at')->nullable();
    $table->timestamps();

});

avis_interventions_tables

    Schema::create('avis_interventions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('qualité');
    $table->integer('nbr_heure');
    $table->string('service');
    $table->float('note', 1,1);
    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('id')->on('clients');
    $table->integer('intervention_id')->unsigned();
    $table->foreign('intervention_id')->references('id')->on('interventions');
    $table->timestamps();
});

интервенции_таблицы

    Schema::create('interventions', function (Blueprint $table) {
    $table->increments('id');
    $table->date('date_intervention')->nullable();
    $table->string('description');
    $table->dateTime('duree_prevu');
    $table->boolean('statut');
    $table->integer('technicien_id')->unsigned();
    $table->foreign('technicien_id')->references('id')->on('techniciens');
    $table->integer('tarification_id')->unsigned();
    $table->foreign('tarification_id')->references('id')->on('tarificationtaches');
    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('id')->on('Clients');


    $table->timestamps();
});

это моя функция

 public function getTar(){
 $tarifications = tarificationtache::with('technicien')->get();

    return $tarifications->map(function ($tarification) {
        return [
            'nom' => $tarification->technicien->user->nom,
            'moyenne_avis' => $tarification->technicien->moyenne_avis,
            'tache' => $tarification->tache->libelle_tache,
            'tarif' => $tarification->tarif,
        ];
    });    


   }

это показано как это

[{"nom":"tech 1","moyenne_avis":null,"tache":"tache 2","tarif":29.55}, 
{"nom":"tech   
2","moyenne_avis":null,"tache":"tache 3","tarif":55.12},{"nom":"tech 
1","moyenne_avis":null,"tache":"tache 3","tarif":253},{"nom":"tech 
2","moyenne_avis":null,"tache":"tache 3","tarif":28.22}]

Json: как добавить среднее значение, чтобы получить среднее значение

Какой у вас ожидаемый JSON? И вы не предоставили схему таблицы taches, пожалуйста, предоставьте.

Ravi Maniyar 26.06.2018 20:24

@RaviManiyar, пожалуйста, смотрите выше, я добавил схему "tache". У меня есть вмешательства, и каждое вмешательство имеет avis_intervention, и каждое вмешательство посвящено одному техническому специалисту. Я хочу отобразить среднее значение avis_intervention, где вмешательство. технический специалист id = tarificationtache.techncien-id

IT2704 27.06.2018 12:03

@RaviManiyar, я хотел бы также вычислить среднее значение «заметки» из таблицы avis $ table-> float ('note', 1,1);

IT2704 27.06.2018 12:41
Как сделать HTTP-запрос в Javascript?
Как сделать HTTP-запрос в Javascript?
В JavaScript вы можете сделать HTTP-запрос, используя объект XMLHttpRequest или более новый API fetch. Вот пример для обоих методов:
0
3
102
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Обновлено:

Ниже приведены файлы моделей, за которыми следует красноречивый запрос о взаимосвязях моделей, который я использовал для генерации вывода:

модель техника:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class technicien extends Model
{
    protected $table = "techniciens";

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

модель тарификации:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\technicien;
use App\tache;
use App\interventions;

class tarificationtache extends Model
{
    protected $table = "tarificationtaches";

    public function technicien()
    {
        return $this->belongsTo('App\technicien', 'technicien_id', 'id');
    }

    public function tache()
    {
        return $this->belongsTo('App\tache', 'tache_id', 'id');
    }

    public function interventions()
    {
        return $this->hasMany('App\interventions', 'technicien_id', 'id');
    }
}

модель таше:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class tache extends Model
{
   protected $table = "taches";
}

модель вмешательств:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\avis_interventions;

class interventions extends Model
{
   protected $table = "interventions";

   public function avis_interventions()
   {
        return $this->hasMany('App\avis_interventions', 'intervention_id', 'id');
   }
}

модель avis_interventions:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class avis_interventions extends Model
{
   protected $table = "avis_interventions";
}

Запрос отношения модели:

$tarifications = tarificationtache::with('technicien')->get();

$results = $tarifications->map(function ($tarification) {
    return [
        'nom' => $tarification->technicien->user->name,
        'moyenne_avis' => $tarification->technicien->moyenne_avis,
        'tache' => $tarification->tache->libelle_tache,
        'tarif' => $tarification->tarif,
        'avg_avis_interventions' => $tarification -> interventions -> count()
    ];
}); 

print_r($results -> toJson());   
exit;

Это возвращает мне ниже вывод:

[{
    "nom": "Ravi-carpenter",
    "moyenne_avis": 2,
    "tache": "Task #1",
    "tarif": 5.22,
    "avg_avis_interventions": 2
}, {
    "nom": "Ravi-carpenter",
    "moyenne_avis": 3.5,
    "tache": "Task #2",
    "tarif": 6.52,
    "avg_avis_interventions": 3
}]

У меня есть эта ошибка «Вызов функции-члена count () при нулевом значении»

IT2704 28.06.2018 10:01

Я отправлю файлы своей модели сегодня, как только у меня будет доступ к моему компьютеру.

Ravi Maniyar 28.06.2018 12:05

@ IT2704 - Я тоже выложил свои модели. Сообщите мне, если это поможет. Спасибо.

Ravi Maniyar 28.06.2018 17:34

у меня есть эта ошибка ('Вызов функции-члена count () при null "')

IT2704 28.06.2018 17:43

Столы пусты? Потому что у меня не было возможности протестировать с пустым набором данных. Но когда у меня есть правильные данные в моих таблицах, это работает.

Ravi Maniyar 28.06.2018 17:57

У меня много вставок в таблице, но я думаю, что синтаксическая ошибка отображения сообщения, потому что у нее нет атрибута для вычисления!.?

IT2704 28.06.2018 18:01

Не могли бы вы опубликовать снимок экрана с подробной ошибкой Laravel здесь?

Ravi Maniyar 28.06.2018 18:09

я добавил экран

IT2704 28.06.2018 19:25

Спасибо за щелчок. Извините, но можете ли вы убедиться, что написание «вмешательств» в контроллере такое же, как и в функции модели?

Ravi Maniyar 28.06.2018 19:31

в изменились на "'avg_avis_interventions' => $ tarification -> interval -> count ()", это работает, но он показал мне это (([{"nom": null, "moyenne_avis": null, "tache": " tache 2 "," tarif ": 29.55," avg_avis_interventions ": 1}, {" nom ": null," mo‌ yenne_avis ": null," ta‌ che ":" tache 3 "," tarif ": 55.12," avg_avis_interventions ": 0}, {" nom ": null," mo‌ yenne_avis ": null," ta‌ che ":" tache 3 "," tarif ": 253," avg_avis_interventions ": 0}, {" nom ": null, "moye‌ nne_avis": null, "tach‌ e": "tache 3", "tarif": 28.22, "avg_avis_interventions": 1}]))

IT2704 29.06.2018 00:03

nom имеет значение null, и мне нравится показывать среднее значение "примечания" из таблицы avis_intervention

IT2704 29.06.2018 00:10
Ответ принят как подходящий
  public function getTar(){
     $tarifications = tarificationtache::with('technicien')->get();

        return $tarifications->map(function ($tarification) {
            return [
                'nom' => $tarification->technicien->user->nom,
                'tache' => $tarification->tache_id,
                'tarif' => $tarification->tarif,
                'avg_avis_interventions' => $tarification->technicien- 
                 >avisinterventions->avg('note')
            ];
        }); 

        print_r($results -> toJson());   
        exit;

   }

Другие вопросы по теме