Laravel显示数据库中的名称

时间:2018-02-16 11:05:35

标签: php mysql laravel blade

我有一个新问题。我会尝试提供足够的信息。

我正在尝试显示访问过客户的员工的姓名,但正如您所看到的那样,它会显示客户的姓名。应该说Madmin(我目前只有一个用户),而不是Bryan或Granucci(这些是客户)。

截图 This is the drafts page

我将在视图,控制器和模型中添加代码。

草稿视图

@extends('app')

@section('content')

@include('nav')

<div class="container">

    @include('flash')

    <div class="row">

        <div class="col-md-2">

            {!! Form::open(['method' => 'GET', 'action' => 'DraftsController@create']) !!}
            {!! Form::submit('Create new draft', ['class' => 'btn btn-primary form-control']) !!}
            {!! Form::close() !!}

        </div>
    </div>

    <hr>

    <div class="row">

        <div class="col-md-12">

            <div class="panel panel-default">

                <div class="panel-heading">Search drafts</div>

                <div class="panel-body">

                {!! Form::open(array('url' => 'drafts/search', 'method' => 'post')) !!}

                <div class="form-group">
                    <div class="col-md-2" align="right">
                        {!! Form::label('customer_name', 'Customer:') !!}
                    </div>
                    <div class="col-md-6">
                        {!! Form::text('customer_name', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
                    </div>
                    <div class="col-md-2" align="right">
                        {!! Form::label('customer_id', 'Customer ID:') !!}
                    </div>
                    <div class="col-md-2">
                        {!! Form::text('customer_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
                    </div>
                </div>

                <br><br>

                <div class="form-group">
                    <div class="col-md-2" align="right">
                        {!! Form::label('descr', 'Article:') !!}
                    </div>
                    <div class="col-md-6">
                        {!! Form::text('descr', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
                        {!! Form::hidden('reportgroup', null, ['class' => 'form-control']) !!}
                    </div>
                    <div class="col-md-2" align="right">
                        {!! Form::label('article_id', 'Article ID:') !!}
                    </div>
                    <div class="col-md-2">
                        {!! Form::text('article_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
                    </div>
                </div>

                <br><br>

                <div class="form-group">
                    <div class="col-md-2" align="right">
                        {!! Form::label('reference', 'Reference:') !!}
                    </div>
                    <div class="col-md-10">
                        {!! Form::text('reference', null, ['class' => 'form-control']) !!}
                    </div>
                </div>

                <br><br>

                <div class="form-group">
                    <div class="col-md-12" align="right">
                        {!! Form::submit('Search', ['class' => 'btn btn-primary form-control']) !!}
                    </div>
                </div>

                {!! Form::close() !!}

                @include('errors')

                </div>

            </div>

            <div class="panel panel-default">

                {!! Form::open(['method' => 'POST', 'action' => 'DraftsController@invoice']) !!}

                <div class="panel-heading">Search results</div>

                <div class="panel-body">
                    <table class="table">
                        <tr>
                            <th>&nbsp;</th>
                            <th>No</th>
                            <th>Employee</th>
                            <th>Customer</th>
                            <th>Reference</th>
                            <th>Draft created</th>
                            <th>Work date</th>
                            <th style="text-align:right">Total excl. VAT</th>
                            <th>&nbsp;</th>
                        </tr>
                        <?php $count = 0; ?>
                        @foreach ($result as $draft)
                            <tr>
                                <td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
                                <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['id'] }}</a></td>
                                <td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
                                <td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
                                <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['reference'] }}</a></td>
                                <td>{{ $draft['created_at'] }}</td>
                                <td></td>
                                <td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
                                <td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
                            </tr>
                            <?php $count++ ?>
                        @endforeach
                    </table>
                    <?php
                    if ($count == 0) {
                        print "No results";
                    }
                    else {
                        ?>
                    <table>
                        <tr>
                            <td>
                                {!! Form::submit('Create invoice for selected drafts', ['class' => 'btn btn-primary form-control']) !!}
                            </td>
                            <td>
                                &nbsp;&nbsp;with invoice date&nbsp;&nbsp;
                            </td>
                            <td>
                                <input class="form-control" name="createDate" type="date" id="createDate" value="{{date('Y-m-d')}}">
                            </td>
                            <td>
                                &nbsp;&nbsp;and mail them to customer&nbsp;&nbsp;
                            </td>
                            <td>
                                <input type="checkbox" id="mailThem" name="mailThem">
                            </td>
                        </tr>
                    </table>

                    {!! Form::close() !!}

                        <?php
                    }
                    ?>
                </div>

            </div>
        </div>

    </div>

</div>
@include('jsonArticles')
@include('jsonCustomers')

<script src="{{ asset('/js/typeahead.js') }}"></script>
<script src="{{ asset('/js/customers.js') }}"></script>
<script src="{{ asset('/js/articles.js') }}"></script>

@stop

Draftsheader Model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class DraftHeader extends Model {

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

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

    public function lines()
    {
        return $this->hasMany('App\DraftLine');
    }

    protected $fillable = [
        'user_id',
        'employee_name',
        'customer_id',
        'name',
        'name2',
        'address',
        'postcode',
        'town',
        'country',
        'reference'
    ];

}

草稿控制器

<?php

namespace App\Http\Controllers;

use Session;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Article;
use App\Customer;
use App\User;
use App\DraftHeader;
use App\DraftLine;
use App\InvoiceHeader;
use App\InvoiceLine;
use App\InvoiceMail;

use App\Http\Requests\DraftRequest;
use App\Http\Requests\DraftSearchRequest;
use App\Http\Requests\DraftLinesRequest;

use App\Http\Controllers\Controller;

use Carbon\Carbon;

class DraftsController extends Controller {
    /*
      |--------------------------------------------------------------------------
      | ArticlesController
      |--------------------------------------------------------------------------
      |
      | Controller for Metis draft tasks
      |
     */

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware('auth:admin');
    }

    /**
     * Get all articles
     *
     * @return array()
     */
    private function allArticles() {
        $allArticles = array();
        $ff = Article::All()->toArray();
        foreach ($ff as $ff1) {
            $allArticles[] = array('name' => $ff1['descr'], 'id' => $ff1['id']);
        }
        return $allArticles;
    }

    /**
     * Get all customers
     *
     * @return array()
     */
    private function allCustomers() {
        $allCustomers = array();
        $ff = Customer::All()->toArray();
        foreach ($ff as $ff1) {
            $allCustomers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
        }
        return $allCustomers;
    }

    /**
     * Get all uers
     *
     * @return array()
     */
    private function allUsers() {
        $allUsers = array();
        $ff = User::All()->toArray();
        foreach ($ff as $ff1) {
            $allUsers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
            //dd($allUsers);
        }
        return $allUsers;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index() {
        // Use request saved in session if applicable
        $result = array();

        if (Session::has('draft_search_request')) {
            $request = Session::get('draft_search_request');
            //dd($request);
            $result = DraftHeader::query();
            if (strlen(trim($request['customer'])) > 0) {
                $result->where('name', 'LIKE', "%" . $request['customer'] . "%");
            }
            if (strlen(trim($request['user'])) > 0) {
                $result->where('name', 'LIKE', "%" . $request['user'] . "%");
            }
            if (strlen(trim($request['reference'])) > 0) {
                $result->where('reference', 'LIKE', "%" . $request['reference'] . "%");
            }
            if (strlen(trim($request['article'])) > 0) {
                $result->DraftLine()->where('descr', 'LIKE', "%" . $request['article'] . "%");
            }
            //dd($result->toSql());
            $result = $result->get()->toArray();
            //dd($result);
        }
        else {
            $result = DraftHeader::query()->where('created_at', '>', Carbon::yesterday())->get()->toArray();
        }
        // Get the total amount for each draft draft
        $totals = array();
        foreach ($result as $value) {
            $total = DraftLine::selectRaw('sum(qty*netamount) AS total')->where('draft_header_id', '=', $value['id'])->get()->toArray();
            $totals[$value['id']] = $total[0]['total'];
        }
        return view('drafts.search')->with('result', $result)->with('totals', $totals)->with('allArticles', $this->allArticles())->with('allCustomers', $this->allCustomers())->with('allUsers', $this->allUsers());
    }

    public function search(DraftSearchRequest $request) {
        //Put request in session variable to use in view
        $request1 = array('customer' => $request['customer'],'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
        if ($request1['customer'] == "" && $request1['user'] == "" &&  $request1['reference'] == "" && $request1['article'] == "") {
            session()->flash('draft_search_request', $request1);
        }
        else {
            Session::put('draft_search_request', $request1);
        }
        return redirect ('drafts');
    }

    public function invoice(Request $request) {
        //Create invoices for the selected drafts
        //dd($request);
        //dd($request->except('_token'));
        $number_of_invoices = 0;
        $draftdeleted = false;
        $mail = false;
        if (isset($request['mailThem']) && $request['mailThem'] == "on") {
            $mail = true;
        }
        $invoicedate = $request['createDate'];
        if (!checkdate(substr($invoicedate, 5, 2), substr($invoicedate, 8, 2), substr($invoicedate, 0, 4))) {
            $invoicedate = "";
        }

        foreach($request->except('_token') as $key => $val) {
            //dd($key);
            if (substr($key, 0, 8) == "invoice_" && $val == "on") {
                $draft_id = substr($key, 8);
                // Create the invoice
                // But only if there are lines
                $draftheader = DraftHeader::findOrFail($draft_id)->toArray();
                $draftlines = DraftHeader::findOrFail($draft_id)->lines()->get()->toArray();
                if (count($draftlines) > 0) {
                    // Create the invoice header
                    $invoiceheader = InvoiceHeader::create($draftheader);
                    if ($invoicedate != "") {
                        $invoiceheader->created_at = $invoicedate;
                        $invoiceheader->save();
                    }
                    // Create the invoice lines
                    foreach ($draftlines as $draftline) {
                        $newline = new InvoiceLine;
                        $newline->article_id = $draftline['article_id'];
                        $newline->descr = $draftline['descr'];
                        $newline->qty = $draftline['qty'];
                        $newline->grossamount = $draftline['grossamount'];
                        $newline->discount = $draftline['discount'];
                        $newline->netamount = $draftline['netamount'];
                        $newline->taxrate = $draftline['taxrate'];
                        $newline->addition = $draftline['addition'];
                        $newline = $invoiceheader->lines()->save($newline);
                    }
                    // Delete the draft
                    DraftHeader::destroy($draft_id);
                    $number_of_invoices++;

                    if ($mail) {
                        // Add the invoice to the create and send queue (no recipient = to be processed)
                        $invoicemail = new InvoiceMail;
                        $invoicemail = $invoiceheader->mail()->save($invoicemail);
                    }
                }
            }
            if (substr($key, 0, 7) == "delete_") {
                // Delete the selected draft
                $draft_id = substr($key, 7);
                DraftHeader::destroy($draft_id);
                session()->flash('flash_success', "Draft deleted");
                $draftdeleted = true;
            }
        }

        $andmailed = "";
        if ($number_of_invoices > 0 && $mail) {
            $andmailed = " and queued to be sent by mail";
        }

        if (!$draftdeleted) {
            session()->flash('flash_success', $number_of_invoices . " invoice(s) created " . $andmailed);
        }

        $request1 = array('customer' => $request['customer'], 'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
        if ($request1['customer'] == "" && ['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
            session()->flash('draft_search_request', $request1);
        }
        else {
            Session::put('draft_search_request', $request1);
        }
        return redirect ('drafts');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create() {
        return view('drafts.create')->with('allCustomers', $this->allCustomers());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(DraftRequest $request) {
        //dd($request);
        // Get the customer information
        /*
        $this->validate($request, [
            'reference' => 'required'
        ]);
         * 
         */
        $customer = Customer::findOrFail($request['customer_id']);
        $pass = array_merge($request->all(), $customer->toArray());
        //dd($pass);
        DraftHeader::create($pass);

        //dd($request);
        // Get the user information
        /*
        $this->validate($request, [
            'reference' => 'required'
        ]);
         * 
         */
        $user = User::findOrFail($request['user_id']);
        $pass = array_merge($request->all(), $user->toArray());
        //dd($pass);
        DraftHeader::create($pass);

        return redirect('drafts');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        // Retrieve header and lines
        //dd($id);
        $draftheader = DraftHeader::findOrFail($id)->toArray();
        //dd($draftheader);

        $draftlines = DraftHeader::findOrFail($id)->lines()->get()->toArray();
        //dd($draftlines);
        // Get the draft's total
        $drafttotal = 0;
        $drafttotal_in = 0;
        foreach ($draftlines as $line) {
            $drafttotal = $drafttotal + ($line['qty'] * $line['netamount']);
            $drafttotal_in = $drafttotal_in + (($line['qty'] * $line['netamount']) / 100 * (100 + $line['taxrate']));
        }
        return view('drafts.edit')->with('header', $draftheader)->with('lines', $draftlines)->with('drafttotal', $drafttotal)->with('drafttotal_in', $drafttotal_in)->with('allArticles', $this->allArticles());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
public function update($id, DraftLinesRequest $request) {
    //dd($request->all());
    // Save the draft header (again)
    $draftheader = DraftHeader::findOrFail($id);
    if ($draftheader->reference != $request['reference']) {
        $draftheader->reference = $request['reference'];
        $draftheader->save();
    }

    // Update the lines if there are changes
    $requestcopy = $request->All();
    reset($requestcopy);
    foreach ($requestcopy as $key => $value) {
        if (substr($key, 0, 11) == "grossamount") {
            $lineid = substr($key, 11);
            $draftline = Draftline::findOrFail($lineid);
            $v_descr = 'descr' . $lineid;
            $v_qty = 'qty' . $lineid;
            $v_grossamount = 'grossamount' . $lineid;
            $v_discount = 'discount' . $lineid;
            $v_addition = 'addition' . $lineid;

            if ($draftline->descr != $request[$v_descr] || $draftline->qty != $request[$v_qty] || $draftline->grossamount != $request[$v_grossamount] || $draftline->discount != $request[$v_discount] || $draftline->addition != $request[$v_addition]) {
                $draftline->descr = $request[$v_descr];
                $draftline->qty = $request[$v_qty];
                $draftline->addition = $request[$v_addition];
                $draftline->grossamount = $request[$v_grossamount];
                $draftline->discount = $request[$v_discount];
                $draftline->netamount = $draftline->grossamount - ($draftline->grossamount * ($draftline->discount/100)) + ($draftline->grossamount * ($draftline->addition/100));
                $draftline->save();
                session()->flash('flash_success', 'Update succeeded');
            }
        }
    }

    // Check if a line needs to be deleted
    reset($requestcopy);
    foreach ($requestcopy as $key => $value) {
        if (substr($key, 0, 6) == "cmdDel") {
            $lineid = substr($key, 6);
            $draftline = Draftline::findOrFail($lineid);
            $draftline->delete();
            session()->flash('flash_success', 'Draft line was deleted');

        }
    }

    // Check if a new line should be created
    if ($request['qty'] != 0 && $request['article_id'] > 0 && strlen($request['descr']) > 0) {
        $newline = new DraftLine;
        $article = Article::findOrFail($request['article_id']);
        $customer = $draftheader->customer;
        $newline->article_id = $request['article_id'];
        $newline->descr = $request['descr'];
        $newline->qty = $request['qty'];
        $newline->grossamount = $article->gross;
        $newline->discount = $customer->discount;
        $newline->taxrate = $article->taxrate;
        if ($customer->taxrate == "No tax") {
            $newline->taxrate = 0;
        }
        $newline->netamount = $newline->grossamount - ($newline->grossamount * ($newline->discount/100));
        $newline = $draftheader->lines()->save($newline);
        session()->flash('flash_success', 'New draft line was added');
    }

    return redirect('drafts/' . $id . '/edit');
}

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        //
    }

}

用户模型

<?php namespace App;

use App\Hour;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Sofa\Eloquence\Eloquence;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;
        use Notifiable;
        use Eloquence;

        public function draftheaders()
        {
            return $this->hasMany('App\DraftHeader');
        }

        protected $searchableColumns = ['name'];
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

        public function hours()
        {
            return $this->hasMany(Hour::class);
        }



}

用户控制器

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

    public function find(Request $request)
    {
        $term = trim($request->q);

        if (empty($term)) {
            return \Response::json([]);
        }

        $users = user::search($term)->limit(5)->get();

        $formatted_users = [];

        foreach ($users as $user) {
            $formatted_users[] = ['id' => $user->id, 'text' => $user->name];
        }

    return \Response::json($formatted_users);

        }
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth')->except('find');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('user');
    }
}

数据库包含以下表格: User tableDraftsheader table

  

在draftsheader表中,我将user_id列更改为index。和   在users表中,我将列名更改为index。通常我会   索引列并给它一个外键。但我看了看   客户表和draftsheader表,那里没有   foreignkeys。所以我在想,也许外国人不是很好的   只要字段被编入索引。

我希望你们可以帮助我,因为我被卡住了...如果缺少信息,现在让我来编辑页面。

更新 在视图中,我将[¨name¨]更改为[¨employee_name¨],如同stackoverflow用户建议的那样。结果如下: Changed name to employee_name

1 个答案:

答案 0 :(得分:0)

尝试更改此内容:

     @foreach ($result as $draft)
                    <tr>
                        <td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
                        <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['id'] }}</a></td>
                        <td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
                        <td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
                        <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['reference'] }}</a></td>
                        <td>{{ $draft['created_at'] }}</td>
                        <td></td>
                        <td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
                        <td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
                    </tr>
                    <?php $count++ ?>
                @endforeach

对此:

         @foreach ($result as $draft)
                        <tr>
                            <td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
                            <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['id'] }}</a></td>
                            <td>{{$draft['employee_name'] }} ({{ $draft['user_id'] }})</td>
                            <td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
                            <td><a href="drafts/{{ $draft['id'] }}/edit">{{ $draft['reference'] }}</a></td>
                            <td>{{ $draft['created_at'] }}</td>
                            <td></td>
                            <td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
                            <td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
                        </tr>
                        <?php $count++ ?>
                    @endforeach

你使用['name']两次,但你有customer_name。