When using Eloquent outside of Laravel and using the Capsule\Manager class, I can't see how to create a SQL view, only a SQL table. When using Eloquent with Laravel, you can do something like:
DB::statement( "CREATE VIEW foo AS SELECT id, name FROM . . .
But the Capsule\Manager class doesn't have a statement() method or any way to execute raw SQL (like the statement() method does) that I can see.
The Capsule\Manager class seems to let you do everything else you can normally do with Eloquent, surely there's a way to create a view?
If you need to execute raw SQL you can use Manager::connection() to get the connection object which has statement and raw methods. Try this:
$db = \Illuminate\Database\Capsule\Manager::connection();
$db->statement($db->raw('CREATE VIEW `foo` AS SELECT * FROM `bar`'));
Related
I am building a Wordpress site and it is connected to a MySQL database. I am using the wordpress class wpdb (https://codex.wordpress.org/Class_Reference/wpdb) to interact with the database. With that class, I am able to query TABLES of my database, but not Views.
I need to be able to select Views of my database. Is this something that is not allowed with wpdb, or is my code just wrong? Is there a way to query views the same way I can query tables using wpdb?
I have tried using the query function, as well as treating a view the same way I treat a table, but it does not work. It returns empty.
Query method:
$test = $mydb->query(
$mydb->prepare(
"
SELECT name FROM $mydb->$view_name
WHERE id = 1"
)
);
echo $test; //returns empty; should return a name
Table method:
$test = $mydb->get_var(
"select name from $view_name WHERE id = 1"
);
echo $test; //returns empty; should return a name
Any suggestions? Am I able to connect to my database using something other than $wpdb (does Wordpress allow that?).
name seems to be a reserved word in MySQL (reference). Try surrounding it with back-ticks (`) like this:
SELECT `name` FROM ...
You should be seeing some errors, do you keep an eye on the logs? Also, when you have doubts in your queries, you can simply copy the raw query and execute it into phpMyAdmin or whatever tool you are using to access your database manually
I would like to know if it's possible to return a MySQL stored procedure call as an eloquent object.
The below call works fine for me, but $result always returns an array instead of the usual Eloquent object.
$result = DB::select('call bookings_by_voucher()');
Does anyone know how to return this as an object, so that I can use ->count(), ->get() etc.
You must pass the array into a new instance of your eloquent object.
$booking = new Booking($result);
A late question, but if anyone else needs this:
Booking::fromQuery('call bookings_by_voucher()');
The only problem is you can't do further sql operations like where, limit, etc, since you can't manipulate a stored procedure directly, eg: you can't do "call bookings_by_voucher() where active = 1 limit 200". You can use laravel collection operations though.
https://laravel.com/docs/5.4/eloquent-collections
you can use eloquent MODEL. It return an object .
ex.
$user = app\ModelName::all()->count();
get(),count() and other aggregate function works with Models
I see you can call my MyModel::all() and then call "where" "groupBy" .. etc
I cant seem to find orderBy as this Q & A suggest..
Has this been removed in Laravel 5?
I've tried looking through the docs for a reference in Collection and Model but I'm assuming these are actually just modifiers for the collection returned and not actually modifying the query statement..
The only way I know of using order by is
\DB::table($table)->where($column)->orderBy($column);
Is that the only way to order your database select when executing a query?
You can actually just use it like where and groupBy:
$result = MyModel::orderBy('name', 'desc')->get();
Note that by calling MyModel::all() you're already executing the query.
In general you can pretty much use every method from the query builder documented here with Eloquent models. The reason for this is that the model proxies method calls (that it doesn't know) to a query builder instance:
public function __call($method, $parameters)
{
// irrelevant code omitted
$query = $this->newQuery();
return call_user_func_array(array($query, $method), $parameters);
}
$this->newQuery() creates an instance of the query builder which then is used to actually run the query. Then when the result is retrieved the model/collection is hydrated with the values from the database.
More info
Eloquent - Laravel 5 Docs
Illuminate\Database\Eloquent\Builder - API docs
And also the regular query builder (since quite a few calls get passed from the eloquent builder)
Illuminate\Database\Query\Builder - API docs
You can achieve this with the following solution:
$result = ModelName::orderBy('id', 'desc')->get();
You can do it by using sort keys
Model::all()->sortKeys()
(or)
Model::all()->sortKeysDesc()
I'm on Laravel and Eloquent, and trying to populate a view's dropdown box with results of a select query.
In my controller:
public function uploadDocs($userid)
{
$doc_options = DB::select('select document.document_description from document where user_id = ?', array($userid));
return View::make('uploaddocs')->with('doc_options', $doc_options);
}
In my view:
<body>
{{ Form::select('doc_options_id', $doc_options) }}
</body>
I'm getting the following stack trace:
htmlentities() expects parameter 1 to be string, object given (View: /home/vagrant/code/eduview/app/views/uploaddocs.blade.php)
Any ideas? Thanks.
Try
$doc_options = DB::statement(DB::raw('select document.document_description from document where user_id = ?', array($userid)))->get();
Edit: I should probably explain first.
DB::select() is primarily used for the database builder in order to chain onto other chain-able functions, and not for doing your whole query.
You could use DB::statement to provide a new custom SQL query in it, but you also have to specify that the contents of the statement()'s parameter will be a raw query. Hence the DB::raw
Alternatively you could take advantage of Eloquent or Laravel's query builder by creating an Eloquent model called Document in app/models with contents as:
class Document extends Eloquent {}
and swap out your query above with:
$doc_options = Document::select('document_description')->where('user_id','=',$userid)->get()
You are passing an object into the Form::select() helper, and it is expecting an array.
Instead, Laravel has tools built in to do just this. See the lists() method in the Laravel docs under Selects:
public function uploadDocs($userid)
{
$doc_options = DB::table('document')->where('user_id', $userid)->lists('document_description');
return View::make('uploaddocs')->with('doc_options', $doc_options);
}
That should be it.
How to do a native sql query in Doctrine 2, executing an update statement?
The createNativeQuery method on EntityManager, requires a second parameter (ResultSetMapping) to be able to map the resultsets to Objects.
But when updating (or inserting, or set, or...) there is no resulset to map.
Passing null or just new ResultSetMapping(), gives an error.
Are only select queries supported for native sql?
Essentially ditto w/ faken,
this from the docs:
If you want to execute DELETE, UPDATE or INSERT statements the Native
SQL API cannot be used and will probably throw errors. Use
EntityManager#getConnection() to access the native database connection
and call the executeUpdate() method for these queries.
one note of use is the connection object can be retrieved from the EntityManager:
$conn = $entityManager->getConnection();
$rowsAffected = $conn->executeUpdate($sql, $params, $types);
Update statements are usually pretty simple, so you might as well use the normal Doctrine2 way (i.e. programmatically updating entities and calling EntityManager::flush() OR using DQL Updates).
Having said this, if you really want to use normal SQL, you could always do it like this:
Keep the db connection object you get when creating a connection with Doctrine2:
$connection = \Doctrine\DBAL\DriverManager::getConnection($dbConfig->toArray(),null,$evm);
Execute whatever SQL you want, using the available methods in the connection object, e.g.:
$connection->executeUpdate($sql, $params, $types);
$connection->exec($sql);
...