我正在尝试使用 laravel 5.1 从 MySQL 数据库中选择记录并将结果分成页面。
这是我用来将数据库结果返回到 listall View 的方法。 (这段代码显示白屏“没有错误,没有结果”)
public function getIndex(){
$accounts = DB::table('accounts')
->lists('account_id','account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
当使用下面的这段代码时,它可以工作,但它会返回所有列。我只想显示 2 列。
public function getIndex(){
$accounts = DB::table('accounts')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
已编辑
这是我在 Kyle 建议“下方”之后的代码
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Accounts;
class AccountsController extends Controller
{
public function getIndex(){
$accounts = Accounts::select('account_id', 'account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
public function getAccounts($id){
return view('accounts.account')->withName('Mike A');
}
}
这是我的账户模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Accounts extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'accounts';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['account_id', 'account_name', 'company_code'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [];
}
但是还是白屏
最佳答案
首先,您不应该使用 DB::table('accounts')
。您应该使用 Account::all()
。虽然我猜这只是语法。
我假设您有一个名为 accounts 的表,该表的两列分别是 account_id
和 account_name
。话虽这么说,你的整个类(class)应该看起来像这样:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Account; //don't forget this so you can use it below
class AccountController extends Controller {
public function getIndex() {
$accounts = Account::select('account_id', 'account_name')
->where('client_id', '=', 7)
->paginate(100);
$name = 'Mike A';
return view('accounts.listall', compact('accounts', 'name'));
}
这是你需要的吗?
关于php - 如何使用 laravel 5.1 从数据库中只选择 2 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598637/