Laravel:在视图中发送数据透视表数据

时间:2016-08-24 10:40:06

标签: php laravel-5 pivot-table

我是Laravel 5的新手,我在数据透视表,控制器和存储库方面遇到了一些困难。

我有表'用户','网站','site_user',这就是我现在拥有的:

应用\模型\用户

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    protected $table = 'users';

    public function sites() 
    {
      return $this->belongsToMany('App\Models\Site')
        ->withPivot('site_id', 'user_id', 'relation');
    }
}

应用\模型\站点

class Site extends Model {

    protected $table = 'sites';

    public function user() 
    {
        return $this->belongsToMany('App\Models\User')
        ->withPivot('site_id', 'user_id', 'relation');
    }
}

应用\库\ SiteRepository

<?php namespace App\Repositories;

use App\Models\Site, App\Models\User;

class SiteRepository extends BaseRepository
{
/**
 * The User instance.
 *
 * @var App\Models\User
 */ 
protected $user;

/**
 * Create a new SiteRepository instance.
 *
 * @param  App\Models\Site $site
 * @return void
 */
public function __construct (Site $sites, User $user)
{
    $this->model = $sites;
    $this->user = $user;
}

/**
 * Get sites collection paginate.
 *
 * @param  int  $n
 * @return Illuminate\Support\Collection
 */
public function index($n)
{
    return $this->model
    ->latest()
    ->paginate($n);
}

应用\ HTTP \控制器\ SiteController

<?php namespace App\Http\Controllers;

use App\Repositories\SiteRepository;
use App\Repositories\UserRepository;
use App\Http\Requests\SiteCreateRequest;
use App\Http\Requests\SiteUpdateRequest;
use App\Models\Site;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SiteController extends Controller {

/**
 * The SiteRepository instance.
 *
 * @var App\Repositories\SiteRepository
 */
protected $site_gestion;

/**
 * The UserRepository instance.
 *
 * @var App\Repositories\UserRepository
 */
protected $user_gestion;

/**
 * Create a new SiteController instance.
 *
 * @param  App\Repositories\SiteRepository $site_gestion
 * @param  App\Repositories\UserRepository $user_gestion
 * @return void
 */
public function __construct (SiteRepository $site_gestion, UserRepository $user_gestion)
{
    $this->site_gestion = $site_gestion;
    $this->user_gestion = $user_gestion;

    $this->middleware('admin');
}

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index(SiteRepository $site_gestion)
{
    //$counts = $this->site_gestion->counts();
    $sites = $site_gestion->index(25);
    $links = $sites->render();
    return view('back.sites.index', compact('sites'));
}

视图\背面\网站\ table.blade.php

@foreach ($sites as $site)
    [...some code...]
@endforeach

我想要的是获取登录用户的所有网站。我尝试了很多东西,但没有一个在起作用。我仍然不确定将代码,存储库或控制器放在哪里......

我已经阅读了有关Laravel中的数据透视的教程,我在repo中试过了类似的东西,但它不起作用......

$user = $this->user->find(auth()->user()->id); //This line is working

foreach ($user->sites as $site) {
    return $site
    ->latest()
    ->paginate($n);
}

2 个答案:

答案 0 :(得分:0)

所以你所做的事情似乎非常接近。

所以你几乎拥有它,当迭代它们应该是站点模型的实例时。

from traits.trait_base import ETSConfig
#ETSConfig.toolkit = "wx"
# fix window color on unity TODO: gets overriden by splitter
if ETSConfig.toolkit == "wx":
    from traitsui.wx import constants
    constants.WindowColor = constants.wx.NullColor

import optparse, logging, urlparse

from capture import BaseCapture, DummyCapture
from bullseye import Bullseye
from process import Process

def main():
   p = optparse.OptionParser(usage="%prog [options]")
   p.add_option("-c", "--camera", default="any:",
           help="camera uri (none:, any:, dc1394://guid/b09d01009981f9, "
                "fc2://index/1, replay://glob/beam*.npz) [%default]")
   p.add_option("-s", "--save", default=None,
           help="save images accordint to strftime() "
                "format string (e.g. 'beam_%Y%m%d%H%M%S.npz'), "
                "compressed npz format [%default]")
   p.add_option("-l", "--log",
           help="log output file [stderr]")
   p.add_option("-d", "--debug", default="info",
           help="log level (debug, info, warn, error, "
                "critical, fatal) [%default]")
   opts, args = p.parse_args()
   logging.basicConfig(filename=opts.log,
           level=getattr(logging, opts.debug.upper()),
           format='%(asctime)s %(levelname)s %(message)s')
   scheme, loc, path, query, frag = urlparse.urlsplit(opts.camera)
   if scheme == "opencv":
       from .opencv_capture import OpenCVCapture
       if loc == "index":
          cam = OpenCVCapture(int(path[1:]))
   elif scheme == "none":
       from capture import DummyCapture
          cam = DummyCapture()
   elif scheme == "any":
       try:
          from .opencv_capture import OpenCVCapture
          cam = OpenCVCapture()
       except Exception, e:
          logging.debug("opencv error: %s", e)
          from capture import DummyCapture
          cam = DummyCapture()
  logging.debug("running with capture device: %s", cam)
  if opts.save:
      cam.save_format = opts.save
  proc = Process(capture=cam)
  bull = Bullseye(process=proc)
  bull.configure_traits()
  bull.close()

if __name__ == "__main__":
    main()

唯一看起来有点奇怪的是你如何定义枢轴。通常在调用$user = auth()->user(); // This is a way of saying your first line without a db query for the user foreach ($user->sites as $site) { // each site in here is a site model $site->pivot->relation; } 时,您不会定义连接ID,如果您希望改变默认值,可以将其作为参数传递给withPivot,如此。

belongsToMany

答案 1 :(得分:0)

如果您希望所记录用户的所有网站都这样做:

$sites = Auth::user()->sites;

这就是你到达这些网站所需要做的一切。如果你想使用查询和分页,请尝试这样:

$sites = Auth::user()->sites()->latest()->paginate($n);