如何连接这两个表以获取结果作为api资源?

时间:2018-08-02 05:00:32

标签: eloquent laravel-5.2

am有两个表,一个是主客户端表,另一个是子客户端表,子客户端是主客户端的客户端,而主客户端的主键在子客户端表中我该如何联接这两个表并在控制器中获取输出以将资源作为JSON传递给API?

这是我主要客户的模型:

 namespace App;

    use Illuminate\Database\Eloquent\Model;

        class Clients extends Model
            {
                  //
                    }

这是我主要客户的控制人:

namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Clients;
    use App\Http\Resources\Client as ClientResource;

        // use Illuminate\Http\Response;

    class Clients_controller extends Controller
        {
          /**
             * Display a listing of the resource.
           *
            * @return \Illuminate\Http\Response
                 */
         public function index()
          {
                   //get clients

                       $clients = Clients::paginate(15);

                   //Return collection of clients as a resource
                   return ClientResource::collection($clients);
              }
                    }

这是我的Sub客户模型:

 namespace App;

            use Illuminate\Database\Eloquent\Model;

            class Sub_clients extends Model
            {
                //
            }

这是我的子客户端控制器:

 namespace App\Http\Controllers;

            use Illuminate\Http\Request;
            use App\Sub_clients;
            use App\Http\Resources\Sub_client as SubclientResource;

            class Sub_client extends Controller
            {
               /**
               * Display a listing of the resource.
              *
                 * @return \Illuminate\Http\Response
              */
          public function index()
           {
                //get Sub_clients

                 $subclients = Sub_clients::paginate(15);

                 //Return collection of sub clients as a resource
                  return SubclientResource::collection($subclients);
             }
                }

由于是laravel的新手,有人可以帮忙吗

1 个答案:

答案 0 :(得分:0)

我使用查询生成器加入

  $client = DB::table('clients')
          ->join('sub_clients', 'clients.c_id', '=', 'sub_clients.c_id')

          ->select('clients.*', 'sub_clients.password', 'sub_clients.username as name')
          ->where('sub_clients.c_id','=',$c_id)

          ->get();