使用eloquent

时间:2017-02-25 07:53:07

标签: eloquent laravel-5.3 vuejs2

我有2个表(项目和客户)。客户可以有很多项目。一个项目属于一个客户。

表架构: 客户端:

Schema::create('clients', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('contact_person');
            $table->timestamps();
        });

项目:

  Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->date('due');
            $table->integer('client_id')->unsigned();
            $table->foreign('client_id')->references('id')->on('clients');
            $table->timestamps();
        });

以下是型号: 客户端型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
  public function projects()
  {
    return $this->hasMany('App\Project');
  }
}

项目模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    public function tasks()
    {
      return $this->hasMany('App\Task');

    }

    public function client()
    {
      return $this->belongsTo('App\Client');
    }
}

这是控制器。 ClientsController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ClientsController extends Controller
{
    public function index()
    {
      $clients = Client::has('projects')->get();
      return $this->hasMany('projects');
    }
}

ProjectsController

<?php

namespace App\Http\Controllers;

use App\Project;
use App\Client;
use Illuminate\Http\Request;


class ProjectsController extends Controller
{
    public function index()
    {
      $projects = Project::find(1)->projects;
      return $projects->all();
    }

    public function store(Request $request)
    {
      return $request->all();
    }
}

Project.vue

  <ul>
    <li v-for="project in projects">
      {{ project.name }} 
      // client's name here
    </li>
  </ul>

我想返回一个查询,相应地显示所有客户的名称和项目名称。我现在能得到的只是项目名称。谢谢。

1 个答案:

答案 0 :(得分:0)

在我发布问题后,我找到了解决方案。在这里。

ProjectsController

<?php

namespace App\Http\Controllers;

use App\Project;
use App\Client;
use Illuminate\Http\Request;


class ProjectsController extends Controller
{
    public function index()
    {
      $projects = Project::with('client')->get();
      return $projects->all();
    }

    public function store(Request $request)
    {
      return $request->all();
    }
}

和Project.vue

<ul>
    <li v-for="project in projects">
      {{ project.name }} || {{project.client.contact_person }}
    </li>
  </ul>